gpt4 book ai didi

c++ - 在 C++ 中有替代的 str.find 吗?

转载 作者:行者123 更新时间:2023-11-27 22:34:41 25 4
gpt4 key购买 nike

我有一个带有字符串的队列 fifo 类型(先进先出)。每个字符串都是句子。我需要在其中找到一个词,并在控制台上显示它。问题是,当我使用 str.find("word") 时,它可以显示带有“words”的句子。

添加空格和一些符号,如“.,?!” = str.find("word ") 等,但这不是解决方案

if (head != nullptr)
do {
if (head->zdanie_kol.find("promotion") != string::npos ||
head->zdanie_kol.find("discount") != string::npos ||
head->zdanie_kol.find("sale") != string::npos ||
head->zdanie_kol.find("offer") != string::npos)
cout << head->zdanie_kol << endl;
} while (head != nullptr);

比如我有两个句子,一个正确,另一个不正确。

正确:

We have a special OFFER for you an email database which allows to contact eBay members both sellers and shoppers.

不正确:

Do not lose your chance sign up and find super PROMOTIONS we prepared for you!

最佳答案

我能想到的三个最简单的解决方案是:

  1. 获得结果后,只需检查下一个字符即可。如果它是空格或 '\0',则您找到了匹配项。确保之前也检查了字符,以便在查找 word 时不匹配 sword。还要确保您没有读取超出字符串内存的内容。
  2. 首先标记字符串。这会将句子分解成单词,然后您可以逐字检查以查看是否匹配。你可以用 strtok() 来做到这一点.
  3. 使用评论中提到的正则表达式(例如 regex_match() )。根据您选择的引擎,语法可能会有所不同,但它们中的大多数都有类似 "\\bsale\\b" 的东西,它将在单词边界上匹配(有关更多信息,请参见 here) .

关于c++ - 在 C++ 中有替代的 str.find 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56266557/

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