从列表中找到另一个字符串中的任意字符串
c++ find any string from a list in another string
我有什么选择从另一个字符串列表中找到任何字符串?
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来表示状态,用映射来表示转换。
如果您的测试用例列表是动态的或者增长得太大,那么手动硬编码状态对您来说是不够的。但是,正如您所看到的,创建状态和转换的规则非常简单。
相关文章:
- 如何在 C++ 中为任意数量的字符串串联编写可变参数函数
- 如何在 Python 或 C++ 中执行任意字符串?
- 在(任意大)流中搜索完全匹配的字符串 - C++
- 使用文件名作为字符串从任意souce .cpp文件中调用函数
- 编译C 程序时具有逻辑错误,该程序应将任意大的数字表示为字符串
- 如何将字符串转换为任意长度的整数
- C++在不使用字符串流的情况下读取具有任意长度和格式的行的多行文件
- 将任意数量的任意类型的值组合为单个字符串的简单命令
- 如何在字符串中的任意位置提取下一个整数
- 如何计算编码在任意字符集中的字符串中的字符数
- 字符串化任意数量的变量
- 如何在C++中围绕任意函数创建字符串参数化包装器
- 取一个包含任意数量单词的字符串,并将这些单词存储在不同的字符串变量中
- 将任意大小的字符串分配给指向char的指针
- Google协议缓冲区和std::字符串用于任意二进制数据
- C++中任意长度字符串的字符串替换
- 获取任意文件的字符串表示形式,c++
- 在c++中搜索任意长度的字符串
- 从列表中找到另一个字符串中的任意字符串
- 从具有任意结构的C++字符串中提取整数