字符串中每个字的频率

时间:2017-07-12 10:46:45

标签: c

我正在编写一些代码,使用strtok()和strstr()函数查找给定字符串中每个单词的频率。我不知道我的代码有什么问题,因为屏幕上没有显示输出。任何人都可以帮助我吗?我是C编程的新手。

#include<stdio.h>
#include<string.h>
void main(){

  char s[2222];
  gets(s);
  char *t,*y=s;
  int count=0;
  t=strtok(s," ,.");

  while(t!=NULL)
  {
    count=0;
    while(y=strstr(y,t))
    {
      y++;
      count++;
    }
    printf("%s appeared %d times.\n",t,count);
    t=strtok(NULL," ,.");
  }
}

2 个答案:

答案 0 :(得分:0)

  1. 您无法使用strstr搜索字词:"is""is this a test?"的出现次数为2,而不是1。
  2. 您不能两次使用strtok;第一次搜索第一次出现,第二次用于后续出现,而不是strstrstrtok正在使用静态变量(请参阅此page中的注释)。
  3. <强> [编辑]

    一个初学者解决方案(run it):

    #include<stdio.h>
    #include<string.h>
    
    #define MAXWORD 32
    typedef struct
    {
      char word[MAXWORD];
      int count;
    } word_and_count_t;
    
    #define MAXWORDCOUNT 1024
    word_and_count_t table[MAXWORDCOUNT];
    
    int table_size;
    
    word_and_count_t* find( const char* word ) // range checking ignored
    {
      int i;
    
      for ( i = 0; i < table_size; ++i )
        if ( !strcmp( table[i].word, word ) )
          return table + i;
    
      strcpy( table[i].word, word );
      table[i].count = 0;
    
      ++table_size;
    
      return table + i;
    }
    
    void display()
    {
      for ( int i = 0; i < table_size; ++i )
        printf( "%s - %d\n", table[i].word, table[i].count );
    }
    
    int main()
    {
      //
      char s[] = "The greatness of a man is not in how much wealth he acquires, but in his integrity and his ability to affect those around him positively.";
    
      //
      for ( char* word = strtok( s, " ,." ); word; word = strtok( 0, " ,." ) )
        find( word )->count++;
    
      //
      display();
    
      return 0;
    }
    

答案 1 :(得分:-3)

我认为主要的问题是你没有提供一个句子来获取这些词语。

char s[2222] = "Enter here the sentence you want to check.";
相关问题