检查一个字符串是否不仅仅包含关键字 C++
Checking if a string contains more than just keywords C++
感谢您点击我的问题。
经过无数小时的搜索,我还没有找到解决方案,而且很难搜索您不知道如何在搜索中正确表达的内容。请帮助我,我将不胜感激。
字符串的数据如下:
std::string keyword 1 "Hello";
std::string keyword 2 "Ola";
std::string test = Keyword1+Keyword2+keyword2;
我试图作为伪代码实现的示例:
if(test.contains(more then the 2 keywords))
我想确保字符串除了上面的关键字之外还有其他文本。
一种可能的解决方案:表示为regular expression, you are testing whether the string matches ^(Hello|Ola)*$
. That is, does the whole string match any number of repeats of "Hello" and/or "Ola" (and with nothing else)? You can use the regex standard library以匹配C++中的正则表达式。
您可以从数据中删除这些关键字的所有实例,看看还剩下什么。它不是非常有效,但对于合理大小的输入应该无关紧要。
bool contains_more_than(std::vector<std::string> const& keywords, std::string sample) {
for (std::string const& keyword: keywords) {
size_t pos;
while ((pos = sample.find(keyword)) != sample.npos) {
sample.replace(pos, keyword.size(), "");
}
}
return !sample.empty();
}
请注意,如果某些关键字是另一个关键字的子字符串,这可能会失败:
contains_more_than({"123", "12345"}, "12345")
returns 正确。
为避免这种情况,您可以先按 std::string::size
:
对关键字进行排序
std::string(keywords.begin(), keywords.end(),
[](std::string const& s1, std::string const& s2) {
return s1.size() > s2.size();
});
现在:
contains_more_than({"12345", "123"}, "12345")
returns 错
感谢您点击我的问题。
经过无数小时的搜索,我还没有找到解决方案,而且很难搜索您不知道如何在搜索中正确表达的内容。请帮助我,我将不胜感激。
字符串的数据如下:
std::string keyword 1 "Hello";
std::string keyword 2 "Ola";
std::string test = Keyword1+Keyword2+keyword2;
我试图作为伪代码实现的示例:
if(test.contains(more then the 2 keywords))
我想确保字符串除了上面的关键字之外还有其他文本。
一种可能的解决方案:表示为regular expression, you are testing whether the string matches ^(Hello|Ola)*$
. That is, does the whole string match any number of repeats of "Hello" and/or "Ola" (and with nothing else)? You can use the regex standard library以匹配C++中的正则表达式。
您可以从数据中删除这些关键字的所有实例,看看还剩下什么。它不是非常有效,但对于合理大小的输入应该无关紧要。
bool contains_more_than(std::vector<std::string> const& keywords, std::string sample) {
for (std::string const& keyword: keywords) {
size_t pos;
while ((pos = sample.find(keyword)) != sample.npos) {
sample.replace(pos, keyword.size(), "");
}
}
return !sample.empty();
}
请注意,如果某些关键字是另一个关键字的子字符串,这可能会失败:
contains_more_than({"123", "12345"}, "12345")
returns 正确。
为避免这种情况,您可以先按 std::string::size
:
std::string(keywords.begin(), keywords.end(),
[](std::string const& s1, std::string const& s2) {
return s1.size() > s2.size();
});
现在:
contains_more_than({"12345", "123"}, "12345")
returns 错