转自:https://blog.csdn.net/zhouxinxin0202/article/details/77862615/ios
C++的string类提供了字符串中查找另外一个字符串的函数find。数组
其重载形式为:函数
string::size_type string::find(string &);spa
功能为在string对象中,查找参数string类型的字符串是否存在,若是存在,返回起始位置。不存在则返回 string::npos。.net
e.g.指针
#include <iostream> #include <string> using namespace std; int main() { string a="abcdefghigklmn"; string b="def"; string c="123"; string::size_type idx; idx=a.find(b);//在a中查找b.
if(idx == string::npos )//不存在。 cout << "not found\n"; else//存在。 cout <<"found\n";
idx=a.find(c);//在a中查找c。 if(idx == string::npos )//不存在。 cout << "not found\n"; else//存在。 cout <<"found\n"; return 0; }
在C语言中,字符串存储为字符数组,以'\0'结束。 在C的接口中,有strstr函数,能够在字符串中查找另外一个字符串。code
char * strstr(const char *str1, const char *str2);对象
功能为在str1中查找str2,若是存在,那么返回查找到的起始指针,不然返回NULL。blog
e.g.接口
#include <iostream> #include <string> #include <cstring>
using namespace std; int main() { string a="abcdefghigklmn"; char *b="def"; char *c="123"; if(strstr(a.c_str(), b) == NULL)//在a中查找b,若是不存在,
cout << "not found\n";//输出结果。
else//不然存在。
cout <<"found\n"; //输出结果。
if(strstr(a.c_str(), c) == NULL)//在a中查找c,若是不存在,
cout << "not found\n";//输出结果。
else//不然存在。
cout <<"found\n"; //输出结果。
return 0; }