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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM