如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:30:35  来源:igfitidea点击:

How to do std::string indexof in C++ that returns index of matching string?

c++stringstl

提问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

Try the findfunction.

试试这个find功能。

Here is the example from the article I linked:

这是我链接的文章中的示例:

 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 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::nposif the string is not found.

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

回答by Perchik

I'm not exactly sure what your example means, but for the stl string class, look into findand rfind

我不太确定你的例子是什么意思,但对于 stl 字符串类,请查看findrfind