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

如题所述

有两种方法可以使用,C++风格,或C风格。
一、C++风格。
C++的string类提供了字符串中查找另一个字符串的函数find。
其重载形式为:
string::size_type string::find(string &);
功能为在string对象中,查找参数string类型的字符串是否存在,如果存在,返回起始位置。不存在则返回 string::npos。
参考代码如下:
#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;
}

二、C语言风格。
在C语言中,字符串存储为字符数组,以'\0'结束。 在C的接口中,有strstr函数,可以在字符串中查找另一个字符串。
char * strstr(const char *str1, const char *str2);
功能为在str1中查找str2,如果存在,那么返回查找到的起始指针,否则返回NULL。
参考代码:
#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中查找b,如果不存在,
cout << "not found\n";//输出结果。
else//否则存在。
cout <<"found\n"; //输出结果。
return 0;
}
温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网