c++ - 在 C++ 字符串中查找完全匹配的单词
问题描述
我有以下字符串:
std::string s1 = "IAmLookingForAwordU and I am the rest of the phrase";
std::string keyWord = "IAmLookingForAword";
我想知道关键字是否完全匹配s1
我用了:
if ( s1.find(keyWord) != std::string::npos )
{
std::cout << "Found " << keyWord << std::endl;
}
但是 find 函数捕获了IAmLookingForAword
inIAmLookingForAwordU
并且 if 语句设置为true
. 但是,我只想捕捉我正在寻找的 keyWork 的完全匹配。
有什么办法可以用 C++ 字符串做到这一点?
解决方案
如果你想留下来,std::string::find
你可以测试单词前后的字符是否超出字符串、标点字符或空格的范围:
bool find_word(const std::string& haystack,const std::string& needle){
auto index = haystack.find(needle);
if (index == std::string::npos) return false;
auto not_part_of_word = [&](int index){
if (index < 0 || index >= haystack.size()) return true;
if (std::isspace(haystack[index]) || std::ispunct(haystack[index])) return true;
return false;
};
return not_part_of_word(index-1) && not_part_of_word(index+needle.size());
}
int main()
{
std::cout << find_word("test","test") << "\n"; // 1
std::cout << find_word(" test ","test") << "\n"; // 1
std::cout << find_word("AtestA","test") << "\n"; // 0
std::cout << find_word("testA","test") << "\n"; // 0
std::cout << find_word("Atest","test") << "\n"; // 0
}
推荐阅读
- php - 在 Ubuntu 16.04 上使用 PHP7.x 安装 Apache 2.2
- python - Python pyglet 不停地重复播放音频
- php - 限制循环的数量,然后将其传递给下一个进程
- c# - c#指纹生物识别,UserConsentVerificationResult()无响应(WPF)
- dvc - 没有导入的派生数据的 DVC 依赖项
- python - 如何使用 Python 将 RGB565 字节数组转换为 RGB888 字节数组?
- c# - 如何首先打开一个窗口,而不是 WPF 中的 MainWindow(C#)
- javascript - 如何在javascript中的字符串内创建嵌套for循环
- metabase - 对远程服务器进行 REST API 调用 - 元数据库
- asp.net - ASP.NET 文件上传不会在更新面板中保留回发文件