STL中的find()函數,提供了強大的功能。
當我們判斷一個字符串是否包含另一個字符串的時候,可以使用find();
如下圖:
#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; }
當然了,上述的idx我們也可以定義成int類型.
實際上,可能定義成int類型更符合我們的認知。代碼如下:
string str1="abcdefghigklmn"; string str2="def"; string str3="123"; int idx = 0; idx = str1.find(str2); cout<<"index_str2 = "<<idx<<endl; idx = str1.find(str3); cout<<"index_str3 = "<<idx<<endl;
我們看下輸出結果:
顯然,str2是str1的字串,返回的是第一個匹配字符的索引;str3不是str1的子串,返回的是-1;因此,我們可以通過返回值idx來確定是不是子串!
如果是子串,則返回非負整數
如果不是子串,則返回-1;