c++ - 如何在整个单词中搜索包含三个以上相同字母的单词

标签 c++

出于某种原因,这段代码打印出我列表中的所有单词,而我希望它只打印出超过三个 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';
            }
        }
    }
    }

最佳答案

有几个问题:

  1. string::find_first_of() 不是正确使用的函数。它在字符串中搜索与参数中指定的任何 字符匹配的第一个字符。换句话说,您的代码确实会查找单个字母 z(因为这是出现在 subString 中的唯一不同字母)。如果您希望在一行中找到三个 z ,请改用 string::find()。如果您希望在字符串中的任意位置找到三个 z,请使用 std::count()

  2. 您没有正确检查返回值。您隐式地将返回值与零进行比较,而您需要与 string::npos 进行比较。

  3. wordIndex++ 放错地方了。

  4. return myWords[wordIndex] 看起来像越界访问,可能导致 undefined behaviour .

关于c++ - 如何在整个单词中搜索包含三个以上相同字母的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18955742/

相关文章:

c++ - CreateFile vs fopen vs ofsteam 优势和劣势?

c++ - is_invocable 具有任意函数参数类型

c++ - 为什么 shared_ptr<T>::use_count() 返回 long 而不是 unsigned 类型?

c++ - 与 glDrawArrays 一起出现的 OpenGL 错误 1280

c++ - 如何使用库分发应用程序?

c++ - 如何简化执行模板函数的 switch 语句?

c++ - 生成文件 - 错误 : file truncated

c++ - 使用 distcc 在 Ubuntu 上的 i686 系统上交叉编译 x86_64

c++ - gdb 列表错误 "No such file or directory"

c++ - 关于多功能的初学者Q