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

发布于 2024-07-14 17:09:27 字数 261 浏览 3 评论 0 原文

我正在寻找 std 命名空间中的字符串 indexof 函数,该函数返回类似于同名 java 函数的匹配字符串的整数。 类似于:

std::string word = "bob";
int matchIndex = getAString().indexOf( word );

其中 getAString() 定义如下:

std::string getAString() { ... }

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 word = "bob";
int matchIndex = getAString().indexOf( word );

where getAString() is defined like this:

std::string getAString() { ... }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

久而酒知 2024-07-21 17:09:27

尝试使用 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;
 }

Try the find function.

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;
 }
虐人心 2024-07-21 17:09:27

您正在寻找 std::basic_string<> 函数模板:

size_type find(const basic_string& s, size_type pos = 0) const;

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

You are looking for the std::basic_string<> function template:

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.

度的依靠╰つ 2024-07-21 17:09:27

从您的示例中不清楚您要在哪个字符串中搜索“bob”,但以下是如何使用 查找

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;
}

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.

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;
}
毁梦 2024-07-21 17:09:27

我不太确定你的示例意味着什么,但对于 stl string 类,请查看 查找 r查找

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文