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

 

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

 

一、string類函數find

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

 

 

二、strstr函數

在C語言中,字符串存儲爲字符數組,以'\0'結束。 在C的接口中,有strstr函數,能夠在字符串中查找另外一個字符串。code

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

功能爲在str1中查找str2,若是存在,那麼返回查找到的起始指針,不然返回NULLblog

 

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; }
相關文章
相關標籤/搜索