c++ 怎样判断字符串string里面是否含有某个字符串

2025-03-28 22:42:56
推荐回答(2个)
回答1:

在C++的STL中,操作字符串的类为string。
string类的成员函数find有一种重载为
int find(const char *s,int pos = 0) const;
功能为从pos开始查找字符串s在当前串中的位置,pos默认值为0,即从开始查找。
find的定义形式,调用形式,与indexof方法均相同,所以在C++中,可以使用string的find函数,实现indexof方法的功能。

~
~

回答2:

代码如下:

#include
using namespace std;

int main()
{
    string s1("ABCDefghIjklmn");
    string::size_type pos = s1.find("DefghIjkl");
    if(pos == string::npos)
        cout << "Not Found." << endl;
    else
        cout << pos << endl;

    return 0;
}

其中pos是原字符串中包含查找字符串的第一个位置。