出于某种原因,这段代码打印出我列表中的所有单词,而我希望它只打印出超过三个 z 的单词
我已经设法解决了代码,下面是搜索其中包含“zz”的单词,例如 buzz 或 blizzard。我的主要目标是搜索整个单词中包含三个 z 的单词,例如 zblizzard 之类的。
Word* Dictionary::findzs()
{
int wordIndex = 0;
cout << "List : " << endl;
while (wordIndex < MAX_WORDS) {
string word1 = myWords[wordIndex]->word;
wordIndex++;
if (word1.find("zz") != std::string::npos){
cout << word1 << endl;
}
}
return 0;
}
更新:
bool has_3_zs(const std::string& s)
{
return std::count(std::begin(s), std::end(s), 'z') >= 3;
}
void Dictionary::has3zs()
{
int wordIndex = 0;
string word = myWords[wordIndex]->word;
while (wordIndex < MAX_WORDS) {
for (auto& s : { word })
{
if (has_3_zs(s))
{
std::cout << s << '\n';
}
}
}
}
最佳答案
有几个问题:
string::find_first_of()
不是正确使用的函数。它在字符串中搜索与参数中指定的任何 字符匹配的第一个字符。换句话说,您的代码确实会查找单个字母z
(因为这是出现在subString
中的唯一不同字母)。如果您希望在一行中找到三个z
,请改用string::find()
。如果您希望在字符串中的任意位置找到三个z
,请使用std::count()
。您没有正确检查返回值。您隐式地将返回值与零进行比较,而您需要与
string::npos
进行比较。wordIndex++
放错地方了。return myWords[wordIndex]
看起来像越界访问,可能导致 undefined behaviour .
关于c++ - 如何在整个单词中搜索包含三个以上相同字母的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18955742/