1. 程式人生 > >轉-C++之string判斷字串是否包含某個子串

轉-C++之string判斷字串是否包含某個子串

 

轉自:https://blog.csdn.net/zhouxinxin0202/article/details/77862615/

 

1、string類函式find

C++的string類提供了字串中查詢另一個字串的函式find。

其過載形式為:

string::size_type string::find(string &);

功能為在string物件中,查詢引數string型別的字串是否存在,如果存在,返回起始位置。不存在則返回 string::npos

 

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; }

 

 

2、strstr函式

在C語言中,字串儲存為字元陣列,以'\0'結束。 在C的介面中,有strstr函式,可以在字串中查詢另一個字串。

char * strstr(const char *str1, const char *str2);

功能為在str1中查詢str2,如果存在,那麼返回查詢到的起始指標,否則返回NULL

 

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; }