C++字符串查找

C++字符串查找教程

C++ 中,我们需要在一个 字符串 中查找一个特定的字符串或者 字符,我们可以使用 find 函数,如果找到,则返回子串或字符在 string 对象字符串中的位置(即下标)。如果查不到,则返回 string::npos。

C++字符串查找find详解

语法

int n = s1.find(s2);

参数

参数 描述
s1 源字符串。
s2 要查找的子串。

返回值

如果找到,则返回子串 s2 在字符串 s1 中的位置,即下标,否则,返回 npos。

说明

我们使用了 find 函数,实现了在字符串 s1 中查找字符串 s2。

案例

字符串查找

C++ find 函数查找字符串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str1 = "Hello HaiCoder"; int findIndex1 = str1.find("HaiCoder"); int findIndex2 = str1.find("haicoder"); cout << "findIndex1 = " << findIndex1 << ", findIndex2 = " << findIndex2 << endl; }

程序运行后,控制台输出如下:

20_C字符串string查找find.png

我们首先,定义了一个字符串 变量 str1,接着,我们使用了字符串的 find 函数,在 str1 中查找字符串 “HaiCoder”,并将结果赋值给变量 findIndex1。

最后,我们再次使用了 find 函数,在字符串 str1 中,查找字符串 haicoder,并将结果赋值给 findIndex2,结果,我们发现,变量 findIndex1 为 6,即,子串 HaiCoder 在字符串 str1 中的位置。

变量 findIndex2 为 -1,即,子串 haicoder 在字符串 str1 中未查找到。

字符串查找

我们可以使用字符串查找,判断字符串中是否包含子串

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; string str1 = "Hello HaiCoder"; string str2 = "HaiCoder"; string str3 = "World"; int n1,n2; if ((n1 = str1.find(str2)) != string::npos) { cout << str1 << " containes " << str2 << endl; } else { cout << str1 << " not containes " << str2 << endl; } if ((n2 = str1.find(str3)) != string::npos) { cout << str1 << " containes " << str3 << endl; } else { cout << str1 << " not containes " << str3 << endl; } }

程序运行后,控制台输出如下:

21_C字符串string查找find.png

我们可以将 find 函数的返回值与 string::npos 进行比较,如果相等,则代表没有找到,否则,代表找到。

C++字符串查找总结

在 C++ 中,我们需要在一个字符串中查找一个特定的字符串或者字符,我们可以使用 find 函数,如果找到,则返回子串或字符在 string 对象字符串中的位置(即下标)。如果查不到,则返回 string::npos。