要从列表中的另一个字符串中找到任何字符串,我有什么选择?
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/