c++ string find函数 c++字符串查找子串方法

std::string的find函数用于查找子串或字符,找到返回索引,未找到返回npos。例如查找"welcome"在字符串中位置为7。可查找字符、指定起始位置,结合循环找所有匹配。相关函数有rfind、find_first_of等,需注意判断npos避免越界。

在C++中,std::string 提供了 find() 函数用于查找子串或字符。它是处理字符串搜索最常用的方法之一,使用简单且功能强大。

find函数基本用法

find() 函数用于在字符串中查找指定的子串或字符,如果找到,返回首次出现的位置(索引),未找到则返回 std::string::npos

函数原型如下:

size_t find(const string& str, size_t pos = 0) const;size_t find(const char* s, size_t pos = 0) const;size_t find(char c, size_t pos = 0) const;

参数说明:

  • str / s / c:要查找的子串、C风格字符串或单个字符
  • pos:从哪个位置开始查找,默认从0开始

返回值:

  • 找到:返回匹配位置的下标(从0开始)
  • 未找到:返回 std::string::npos(通常为 -1 转换为无符号数)

查找子串示例

以下代码演示如何使用 find 查找子字符串:

#include iostream>
#include
using namespace std;

int main() {
string text = "Hello, welcome to C++ programming!";
string pattern = "welcome";

size_t found = text.find(pattern);
if (found != string::npos) {
cout } else {
cout }
return 0;
}

输出结果:

子串 'welcome' 在位置 7 找到。

查找字符或从指定位置查找

find 也可以用来查找单个字符,或者从某个偏移位置开始搜索:

// 查找字符
size_t pos = text.find('C'); // 找第一个 'C'

// 从位置10开始查找子串
size_t pos2 = text.find("programming", 10);

还可以结合循环查找所有匹配位置:

string str = "ababa";
string target = "aba";
size_t pos = 0;
while ((pos = str.find(target, pos)) != string::npos) {
cout pos += 1; // 避免死循环,向前移动一位继续找
}

其他相关的查找函数

C++ string 还提供了几个类似的查找函数,适用于不同场景:

  • rfind():从右往左查找,返回最后一次出现的位置
  • find_first_of():查找任意一个指定字符首次出现的位置(如空格、标点)
  • find_last_of():查找任意一个指定字符最后一次出现的位置
  • find_first_not_of()find_last_not_of():查找不在指定集合中的字符

例如:

string s = "hello world!";
size_t p = s.find_first_of(" ,!"); // 查找第一个空格或标点
cout

基本上就这些。熟练掌握 find 及其变体,能高效完成大多数字符串查找任务。注意判断返回值是否为 npos,避免越界访问。不复杂但容易忽略细节。