判断一个字符串是否是另一个字符串的子串。

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类型.

猜你喜欢

转载自www.cnblogs.com/shaonianpi/p/12733238.html