我正在寻找std命名空间中的字符串indexof函数,它返回一个匹配字符串的整数,类似于同名的java函数.就像是:
std::string word = "bob";
int matchIndex = getAString().indexOf( word );
Run Code Online (Sandbox Code Playgroud)
其中getAString()的定义如下:
std::string getAString() { ... }
Run Code Online (Sandbox Code Playgroud)
And*_*are 29
试试这个find
功能.
以下是我链接的文章中的示例:
string str1( "Alpha Beta Gamma Delta" );
string::size_type loc = str1.find( "Omega", 0 );
if( loc != string::npos ) {
cout << "Found Omega at " << loc << endl;
} else {
cout << "Didn't find Omega" << endl;
}
Run Code Online (Sandbox Code Playgroud)
您正在寻找的std::basic_string<>
功能模板:
size_type find(const basic_string& s, size_type pos = 0) const;
Run Code Online (Sandbox Code Playgroud)
std::string::npos
如果未找到该字符串,则返回索引。
从你的例子中不清楚你在搜索"bob"中的String,但是这里是如何使用find在C++中搜索子字符串.
string str1( "Alpha Beta Gamma Delta" );
string::size_type loc = str1.find( "Omega", 0 );
if( loc != string::npos )
{
cout << "Found Omega at " << loc << endl;
}
else
{
cout << "Didn't find Omega" << endl;
}
Run Code Online (Sandbox Code Playgroud)