C/C++判断字符串是否包含某个子字符串

 1 C风格
 2 
 3 #include <iostream>
 4 #include <string>
 5 #include <cstring>
 6 using namespace std;
 7 int main()
 8 {
 9     string a="abcdefghigklmn";
10     char *b="def";
11     char *c="123";
12      
13     if(strstr(a.c_str(), b) == NULL)//在a中查找b,如果不存在,
14         cout << "not found\n";//输出结果。
15     else//否则存在。
16         cout <<"found\n"; //输出结果。
17     if(strstr(a.c_str(), c) == NULL)//在a中查找b,如果不存在,
18         cout << "not found\n";//输出结果。
19     else//否则存在。
20         cout <<"found\n"; //输出结果。
21     return 0;
22 }
23  
24 C++风格
25 #include <iostream>
26 #include <string>
27 using namespace std;
28 int main()
29 {
30     string a="abcdefghigklmn";
31     string b="def";
32     string c="123";
33     string::size_type idx;
34      
35     idx=a.find(b);//在a中查找b.
36     if(idx == string::npos )//不存在。
37         cout << "not found\n";
38     else//存在。
39         cout <<"found\n"; 
40     idx=a.find(c);//在a中查找c。
41     if(idx == string::npos )//不存在。
42         cout << "not found\n";
43     else//存在。
44         cout <<"found\n"; 
45     return 0;
46 }

摘自:https://www.cnblogs.com/ceerqingting/p/10559644.html

posted @ 2020-12-01 15:20  小小的星辰  阅读(2432)  评论(0编辑  收藏  举报