1. 程式人生 > >c++ 怎樣判斷字串string裡面是否含有某個字串?

c++ 怎樣判斷字串string裡面是否含有某個字串?

c++ string怎樣判斷字串裡面是否含有某個字串?
例如:string str="afdsdfs_hello_sdfas#@!";
怎樣判斷str裡面是否含有“hello",,謝謝
 
使用 string 的 find 成員函式。 
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "afdsdfs_hello_sdfas#@!";
string str1 = "hello";

string::size_type idx = str.find( str1 );

if ( idx != string::npos )
{
cout << "字串含有“<< str1 << "\n";
}
else
{
cout << "字串沒有" << str1 << "\n";
}
}
解析:string::npos是個返回值


string 類提供了 6 種查詢函式,每種函式以不同形式的 find 命名。
這些操作全都返回 string::size_type 型別的值,以下標形式標記查詢匹配所發生的位置;或者返回一個名為 string::npos 的特殊值(它說明查詢沒有匹配的)。string 類將 npos 定義為保證大於任何有效下標的值。

所以 當 str.find("哦")==string::npos時則說明字串str中不存在“哦”這個字元,
反之,str.find("哦")!=string::npos則說明字串str中存在“哦”這個字元