gpt4 book ai didi

c - 如何用 C 语言编写代码来检查字符串中的重复单词并计算它们出现的次数?

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

我现在正在为我的类(class)编写一段代码,用于分析手动插入的文本。我应该找到非空格字符的总数和单词总数。另外,我应该找到字符串中任何重复的单词,然后显示它们的重复次数。我陷入了寻找重复单词并显示重复次数的困境。另外,我对 C 的了解有限,我所知道的主题包括指针、字符串、文件和函数、循环、if 条件等......下面是我到目前为止的代码:

#include <stdio.h>

int num, numi, text, length, length1, word;
numi = 0;
word = 1;

int main()
{
char text[] = "Dennis MacAlistair Ritchie (September 9, 1941 - October 12, 2011) was an American computer scientist. He created the C programming language and, with long-time colleague Ken Thompson, the Unix operating system and B programming language. Dennis Ritchie was born in Bronxville, New York. His father was Alistair E. Ritchie, a long-time Bell Labs scientist and co-author of The Design of Switching Circuits on switching circuit theory. As a child, Dennis moved with his family to Summit, New Jersey, where he graduated from Summit High School. He graduated from Harvard University with degrees in physics and applied mathematics.";
printf("Welcome to UNM Text Editor. Your original text is:\n\n");
printf("%s", text);
length = strlen(text);
for (numi=0; numi<=length; numi++)
{
if (text[numi] == ' ')
{
length1++;
if (text[numi + 1] != ' ')
{
word++;
}
}
}
printf("\n\nThe total number of characters (without spaces) is: %d", length-length1);
printf("\nThe total number of words is: %d", word);
}

最佳答案

根据我在评论中读到的内容,您已经解决了前两点,因此我将主要关注重复。

为此,您可以使用 Trie 数据结构,请查看下面的链接。

https://www.geeksforgeeks.org/trie-display-content/

它是用 C++ 编写的,但真正使用 C++ 中的东西并不多,因此可以轻松地将其重写为 C。您只需在 GeeksForGeeks 代码中添加几行即可使其工作。因为这是你的类(class)作业,也许你不应该只使用整个代码,而应该编写自己的代码,但我想向你展示总体想法,

  1. 将可变数量的“string”添加到结构中:


    struct TrieNode
    {
    struct TrieNode* children[alpha_size];
    bool isLeaf;
    int occurrence; // <-- I ADDED IT HERE
    }

  2. 在insert_node_function末尾添加:


    ...
    pCrawl->isLeaf = true;
    pCrawl->occurrence++; // <-- I ADDED IT HERE
    ...

  3. 仅当出现次数大于1时显示

    <p></p>

    <p>void display(struct TrieNode* root, char str[], int level)
    {
    // If node is leaf node, it indicates end
    // of string, so a null character is added
    // and string is displayed
    if (isLeafNode(root) && root->occurrence > 1) // <-- I ADDED IT HERE
    {
    str[level] = '\0';
    cout << str << " " << root->occurrence << endl; // <-- I ADDED IT HERE
    }
    ...
    </p>

剩下的一件事是如何从“文本”(示例中的字 rune 本)中读取单个单词。为了方便起见,您可以删除所有重复的空格并再次浏览文本。然后,您可以复制将空格作为分隔符的单词(例如通过使用 strncat)并插入到 trie 中。

要了解 trie 的工作原理,请尝试用 google 搜索它。应该有很多关于它的信息。

关于c - 如何用 C 语言编写代码来检查字符串中的重复单词并计算它们出现的次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59633597/

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