简体   繁体   English

字符串中每个单词的频率

[英]Frequency of every Word in a String

I am writing some code which finds the frequency of every word in a given string using the strtok() and the strstr() functions. 我正在编写一些代码,使用strtok()和strstr()函数查找给定字符串中每个单词的出现频率。 I don't know what is the problem with my code as no output is being displayed on the screen. 我不知道我的代码有什么问题,因为屏幕上没有显示输出。 Can anyone help me?I am new to C programming. 谁能帮我?我是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," ,.");
  }
}
  1. You cannot use strstr to search for words: the number of occurrence of "is" in "is this a test?" 您不能使用strstr搜索单词: "is this a test?""is"的出现次数。 is two, not one. 是两个,不是一个。
  2. You cannot use strtok two times; 您不能使用strtok两次; first time to search for first occurrence and second time for subsequent occurrences, instead of strstr : strtok is using a static variable (see the note in this page ). 第一次搜索第一次出现,第二次搜索后续出现,而不是strstrstrtok使用静态变量(请参阅本页中的注释)。

[EDIT] [编辑]

A begginner solution ( 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;
}

我认为主要的问题是您没有提供句子来获得这些单词。

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

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

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