gpt4 book ai didi

C++ 多次在字符串中查找单词

转载 作者:行者123 更新时间:2023-11-30 03:26:54 26 4
gpt4 key购买 nike

我目前正在尝试在字符串中查找单词。我正在使用 string::find()。然而,这只会在字符串中找到该单词一次。

string a = "Dog";
string b = "I have a dog, his name is dog";

if (b.find(a) != string::npos)
{
...
}

有没有办法扫描字符串 b 以查看单词“dog”出现了多少次?

最佳答案

使用循环,直到找不到为止。

std::size_t count = 0, pos = 0;
while ((pos = b.find(a, pos)) != std::string::npos) {
pos += a.size(); // Make sure the current one is skipped
count++;
}
// Now you have count

关于C++ 多次在字符串中查找单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47843152/

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