gpt4 book ai didi

c++ - 如何在 C++ 的字符串中找到一个完整的单词(不是它的一部分)

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:49 26 4
gpt4 key购买 nike

在 C++ 代码中,我试图在句子中搜索单词,但它一直在进行部分搜索。我希望它只搜索完整的单词而不是部分单词,有什么帮助吗?

size_t kk;
string word="spo";
string sentence="seven spoons";

kk=sentence.find(word);
if (kk !=string::npos)
cout << "something" << endl;

最佳答案

听起来你想要的是由正则表达式中的单词边界或单词字符的概念处理的。

这是一个只返回完整匹配项的程序。也就是说,它只会返回与您要搜索的确切词完全匹配的词。如果 sentence 中的某些单词将您的目标单词作为严格子字符串,则不会返回它。

#include <regex>
#include <string>
#include <iostream>

int main() {
std::string word = "spo"; // spo is a word?
std::string sentence = "seven spoons";

std::regex r("\\b" + word + "\\b"); // the pattern \b matches a word boundary
std::smatch m;

if (std::regex_search(sentence, m, r)) { // this won't find anything because 'spoons' is not the word you're searching for
std::cout << "match 1: " << m.str() << '\n';
}

sentence = "what does the word 'spo' mean?";
if (std::regex_search(sentence, m, r)) { // this does find the word 'spo'
std::cout << "match 2: " << m.str() << '\n';
}
}

或者您的意思是您想要找到与您正在搜索的部分词相匹配的任何词。正则表达式也可以做到这一点:

  std::string partial_word = "spo";
std::regex r("\\w*" + partial_word + "\\w*"); // the pattern \w matches a word character

这会产生:

match 1: spoons
match 2: spo

关于c++ - 如何在 C++ 的字符串中找到一个完整的单词(不是它的一部分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22516463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com