【问题标题】:How to do std::string indexof in C++ that returns index of matching string?如何在 C++ 中执行 std::string indexof 返回匹配字符串的索引?
【发布时间】:2010-10-13 16:24:03
【问题描述】:

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

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

getAString() 的定义如下:

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

【问题讨论】:

    标签: c++ string stl


    【解决方案1】:

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

    【讨论】:

    • 是否有一个函数可以实际找到子字符串开始的index?我可以减去开始的迭代器,但这有必要吗?
    • @ArnavBorborah find 返回索引。无符号整数类型string::size_type 只是为了保证find 的结果适合loc。 (想想一个非常非常大的索引可能不适合int。)stackoverflow.com/questions/1181079/…
    【解决方案2】:

    您正在寻找std::basic_string&lt;&gt; 函数模板:

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        从您的示例中不清楚您要在哪个字符串中搜索“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;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-12
          • 2011-06-13
          相关资源
          最近更新 更多