【发布时间】:2010-10-13 16:24:03
【问题描述】:
我正在从 std 命名空间中寻找一个字符串 indexof 函数,它返回一个匹配字符串的整数,类似于同名的 java 函数。比如:
std::string word = "bob";
int matchIndex = getAString().indexOf( word );
getAString() 的定义如下:
std::string getAString() { ... }
【问题讨论】:
我正在从 std 命名空间中寻找一个字符串 indexof 函数,它返回一个匹配字符串的整数,类似于同名的 java 函数。比如:
std::string word = "bob";
int matchIndex = getAString().indexOf( word );
getAString() 的定义如下:
std::string getAString() { ... }
【问题讨论】:
试试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;
}
【讨论】:
find 返回索引。无符号整数类型string::size_type 只是为了保证find 的结果适合loc。 (想想一个非常非常大的索引可能不适合int。)stackoverflow.com/questions/1181079/…
您正在寻找std::basic_string<> 函数模板:
size_type find(const basic_string& s, size_type pos = 0) const;
如果找不到字符串,则返回索引或std::string::npos。
【讨论】:
从您的示例中不清楚您要在哪个字符串中搜索“bob”,但这里是如何使用 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;
}
【讨论】: