如何在C++中执行std :: string indexof,返回匹配字符串的索引?

Ale*_*x B 19 c++ string stl

我正在寻找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)


dir*_*tly 6

您正在寻找的std::basic_string<>功能模板:

size_type find(const basic_string& s, size_type pos = 0) const;
Run Code Online (Sandbox Code Playgroud)

std::string::npos如果未找到该字符串,则返回索引。


Bil*_*ard 6

从你的例子中不清楚你在搜索"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)