find_first_of()
、find()
、strstr()
find_first_of()
查找的是子串中任意字符首次出现的位置。而find()
是查找子串整体出现的位置。
string str1 = "ahedhello111";
string str2 = "hello";
string str3 = "helle";
cout << "find first of str2: " << str1.find_first_of(str2) << endl; //返回1
cout << "find first of str3: " << str1.find_first_of(str3) << endl; //返回1
cout << "find str2: " << str1.find(str2) << endl; //返回即子字符串索引4
cout << "find str3: " << str1.find(str3) << endl; //查找失败,返回-1
strstr()
也是查找子串整体,与find()不同的是处理类型不同。strstr()处理的是char*
。
- 函数原型:
char *strstr(const char *str1, const char *str2);
- 返回值:成功找到,返回在父串中第一次出现的位置的 char *指针;若未找到,即不存在这样的子串,返回 NULL。
char a[] = "ahedhello111";
char b[] = "dda";
char *rel = strstr(a, b); //首次出现地址,strstr保存的是ddabc
if (rel != NULL)
j = rel -a; //根据返回子字符串匹配结果输出索引位
参考:
[1]C/C++库函数strstr和find实现子字符串查找
[2]【C/C++】关于strstr函数和c_str()函数