繁体   English   中英

计算字符串中出现的单词

[英]Counting words occurrence in a string

我正在尝试计算字符串中出现的单词。 对于字符串 S,我需要显示每个单词以及该单词在字符串中出现的次数。

例子:

string = ";! one two, tree foor one two !:;"

结果:

one: 2
two: 2
tree: 1
foor: 1

这是我的代码,但它没有返回正确的计数:

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

int count_word(char * mot, char * text) {
  int n = 0;
  char *p;

  p = strstr(text, mot);

  while (p != NULL) {
    n++;
    p = strstr(p + 1, mot);
  }  

  return n;
}

void show_all_words(char * text) {
    char * p = strtok(text, " .,;-!?");

    while (p != NULL) {
      printf ("%s : %d\n", p, count_word(p, text));
      p = strtok(NULL, " .,;-!?");
    }
}

int main(char *argv[]) {

    char text[] = ";! one two, tree foor one two !:;";
    show_all_words(&text);

    return (EXIT_SUCCESS);
};

它回来了:

one : 1
two : 0
tree : 0
foor : 0
one : 1
two : 0
: : 0

函数strtok更改其参数。 您可以通过复制字符串、在一个副本上调用strtok在另一个副本上调用count_word来解决该问题。

另外,请注意不要两次输出同一个单词的计数。

int count_word(char * mot, char * text, int offset) {
  int n = 0;
  char *p;

  p = strstr(text, mot);
  assert(p != NULL);
  if (p - text < offset)
      return -1; // if the word was found at an earlier offset, return an error code 

  while (p != NULL) {
    n++;
    p = strstr(p + 1, mot);
  }  

  return n;
}

void show_all_words(char * text) {
    char *text_rw = strdup(text); // make a read-write copy to use with strtok
    char * p = strtok(text_rw, " .,;-!?");

    while (p != NULL) {
      int offset = p - text; // offset of the word inside input text
      int count = count_word(p, text, offset);
      if (count != -1) // -1 is an error code that says "already looked at that word"
          printf ("%s : %d\n", p, count );
      p = strtok(NULL, " .,;-!?");
    }
    free(text_rw); // delete the copy
}

你应该改变方法。 您可以使用数组来存储每个单词的首次出现索引和出现次数。 仅在字符串中旅行一次,但在辅助数组中旅行更多次,以检查当前单词是否已被计数。

我希望对你有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM