首页 > 解决方案 > 在 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 函数捕获了IAmLookingForAwordinIAmLookingForAwordU并且 if 语句设置为true. 但是,我只想捕捉我正在寻找的 keyWork 的完全匹配。

有什么办法可以用 C++ 字符串做到这一点?

标签: c++c++11

解决方案


如果你想留下来,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
}

推荐阅读