从列表中找到另一个字符串中的任意字符串

c++ find any string from a list in another string

本文关键字:字符串 任意 另一个 列表      更新时间:2023-10-16

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

s是一个std::字符串,我尝试

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

我想找到这些字符串中的第一个并得到它在字符串中的位置;因此,如果s是"My cat is sleepingn",我将得到3作为返回值。

boost::to_upper(s);

您可以使用正则表达式。

我不认为有一种方法可以直接获得匹配的位置,所以首先你必须搜索正则表达式,如果有匹配,你可以搜索那个字符串。这样的:

#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main() {
    string s = "My cat is sleepingn";
    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;
}

您可以将您的搜索案例转换为DFA。这是最有效的方法。

:

nil, c, ca, cat., d, do, dog., co, cow., m, mo, mou, mous, mouse.

转换表:

state | on | goto
nil   | c  | c
nil   | d  | d
nil   | m  | m
c     | a  | ca
c     | o  | co
d     | o  | do
m     | o  | mo
ca    | t  | cat.
co    | w  | cow.
do    | g  | dog.
mo    | u  | mou
mou   | s  | mous
mous  | e  | mouse.
*     | *  | nil

你可以用很多中间函数来表达。使用了很多开关。或者用enum来表示状态,用映射来表示转换。

如果您的测试用例列表是动态的或者增长得太大,那么手动硬编码状态对您来说是不够的。但是,正如您所看到的,创建状态和转换的规则非常简单。