c - 如何计算字符串中每个单词的出现次数?

标签 c arrays string pointers

我想弄清楚如何计算用户输入的字符串中每个单词的出现次数。我想使用一个数组作为输入,并将每个元素/单词复制到另一个数组(单词)中,前提是该单词尚未被复制。如果它已被复制,我只想通过使用并行计数器数组 (count) 来增加出现次数。到目前为止,我已经编译了,但是当我运行程序时,它只为所有计数值提供 0,并且它仍然打印字符串中的每个单词,即使它之前已经打印过。任何帮助将不胜感激!

#include <stdio.h>
#include <string.h>

#define STR_LEN 1000
int read_line(char *str, int n);

int main() {
    char input[STR_LEN + 1];
    char *token;
    char words[50];
    char *p1;
    char *p2;
    int i;
    int count[50] = { 1 };

    printf("Please enter a string: ");
    read_line(input, STR_LEN);   //Calls the readline function

    printf("Input: %s\n", input);
    for (i = 0; i < strlen(input); i++) {
        p1 = &input[i];
        p2 = &words[i];
        if (strstr(p1, input) == 0) {
            strcpy(p2, p1);
        } else
            count[i]++;     
    }
    printf("Output: \n");
    token = strtok(words, " ,.!");  //tokenizes the first word in the string

    while (token != NULL) {    
        printf("%s\t\t%d\n", token, count[i]);
        token = strtok(NULL, " ,.!");  //tokenizes subsequent words in the string
    } 
    return 0;
}

int read_line(char *s1, int n) {
    int ch, i = 0;

    while ((ch = getchar()) != '\n') {
        if (i < n) {
            *s1++ = ch;
            i++;
        }
    }
    *s1 = '\0';  //terminates string
    return i;    //number of characters stored
}

最佳答案

words 应该使用字符串数组而不是字符数组:

char *words[50];

您应该使用 strdup() 分配单词的副本。

你的主循环不一致,你没有匹配单词,你为字符串中的每个偏移量查找字符串片段。将标记化代码移到循环中并匹配字符串,而不是字符。

关于c - 如何计算字符串中每个单词的出现次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35976613/

相关文章:

c - 传递一个二维数组给函数

php - 将 MySQL 查询转换为多维数组

c - C中的动态分配

perl - Perl 中单引号和双引号有什么区别?

Java : Index out of bound exception when creating a string with no matching consecutive characters

c - C 程序查找数据类型中位数的问题

c - 打印链表当前节点的下一个元素

c - 在 C 中暂停线程一秒钟

c - 将 Log_2 的位旋转破解扩展到 64 位

python - Pandas :计算字符串中的点 - 与长度相同?