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 "; else//存在。 cout <<"found "; idx=a.find(c);//在a中查找c。 if(idx == string::npos )//不存在。 cout << "not found "; else//存在。 cout <<"found "; 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;