c++从另一个字符串中的列表中找到任何字符串

标签 c++

要从列表中的另一个字符串中找到任何字符串,我有什么选择?

s 是一个 std::string,我试过了

s.find("CAT" || "DOG" || "COW" || "MOUSE", 0);

我想找到这些字符串中的第一个并在字符串中找到它的位置;所以如果 s 是“我的猫正在 sleep \n”,我会得到 3 作为返回值。

boost::to_upper(s);

已应用(对于那些想知道的人)。

最佳答案

您可以使用正则表达式来做到这一点。

我认为没有办法直接获取匹配项的位置,因此首先您必须搜索正则表达式,如果有匹配项,您可以搜索该字符串。像这样:

#include <iostream>
#include <string>
#include <regex>

using namespace std;

int main() {
    string s = "My cat is sleeping\n";
    smatch m;
    regex animal("cat|dog|cow|mouse");

    if (regex_search (s,m,animal)) {
        cout << "Match found: " << m.str() << endl;
        size_t match_position = s.find(m.str());

        // In this case it is always true, but in general you might want to check
        if (match_position != string::npos) {
            cout << "First animal found at: " << match_position << endl;
        }
    }
    return 0;
}

关于c++从另一个字符串中的列表中找到任何字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31405415/

相关文章:

c++ - C++ 中的 clr 托管 - 程序集路径

c++ - 在类模板中为成员函数定义单个模板,并在成员函数中使用两个模板

c++ - **在C/C++中是什么意思?

c++ - 如何检查鼠标在最后 5 秒内没有移动?

c++ - 用复数解析表达式

c++ - 同一个词加了两次

c++ - Qt:如何固定 QTreeWidget 的列宽?

c++ - 带有模板参数的 make_tuple 不编译

c++ - 为什么当新数组、调整 vector 大小和push_back到 vector 时会出现bad_alloc?

c++ - 在 C++ 代码中创建 XML