如何在 C++ 中执行 std::string indexof 返回匹配字符串的索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/651497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do std::string indexof in C++ that returns index of matching string?
提问by Alex B
I'm looking for a string indexof function from the std namespace that returns an integer of a matching string similar to the java function of the same name. Something like:
我正在寻找 std 命名空间中的 string indexof 函数,该函数返回一个匹配字符串的整数,类似于同名的 java 函数。就像是:
std::string word = "bob";
int matchIndex = getAString().indexOf( word );
where getAString() is defined like this:
其中 getAString() 定义如下:
std::string getAString() { ... }
回答by Andrew Hare
回答by Bill the Lizard
It's not clear from your example what String you're searching for "bob" in, but here's how to search for a substring in C++ using find.
从您的示例中并不清楚您要在哪个字符串中搜索“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;
}
回答by dirkgently
You are looking for the std::basic_string<>
function template:
您正在寻找std::basic_string<>
功能模板:
size_type find(const basic_string& s, size_type pos = 0) const;
This returns the index or std::string::npos
if the string is not found.
std::string::npos
如果未找到该字符串,则返回索引。