计算机考研|C语言——从字符串中统计单词的频数

C语言——从字符串中统计单词的频数

#include #include #includetypedef struct node{ char word[20]; int count; struct node* next; }node; typedef node* LinkList; LinkList InitList(); void GetWord(char *s,LinkList head); void WordToLinkList(LinkList head,char* s); void PrintList(LinkList head); int main(){ char str[10000]={'\0'}; char temp[1000]; char path[] = "number.in"; FILE* in = fopen(path,"r"); if(!in){ printf("File can't be opened!\n"); exit(0); } while(fgets(temp,sizeof(temp),in)!=NULL){ if(temp[strlen(temp)-1] == '\n')//去掉每一行末尾的换行符 temp[strlen(temp)-1] = '\0'; strcat(str,temp); //将所有行的字符合并到一行 } LinkList head = InitList(); //初始化链表 GetWord(str,head); //获取单词并添加到链表中 PrintList(head); fclose(in); system("pause"); return 0; }LinkList InitList(){//初始化链表,获得头结点 LinkList head = (LinkList)malloc(sizeof(node)); head->word[0] = '\0'; head->next = NULL; return head; }void GetWord(char *s,LinkList head){ char *p; char delim[] = " ,."; //分隔符 p = strtok(s,delim); //将字符串按照分隔符进行分隔 //strtok函数只是将分隔符都设置为'\0',并没有生成多个字符串,采用 while(p!=NULL){ WordToLinkList(head,p); //将每一个单词传进链表中,生成结点 p = strtok(NULL,delim); //p继续指向下一个字符串开头 } }void WordToLinkList(LinkList head,char* s){ LinkList q = head->next; int isExit = 0; while(q){ if(strcmp(q->word,s)==0){//存在结点,计数值+1 q->count++; isExit = 1; break; } q = q->next; } if(!isExit){//不存在则创建结点 LinkList temp = (LinkList)malloc(sizeof(node)); strcpy(temp->word,s); temp->count=1; temp->next = head->next; head->next = temp; } }void PrintList(LinkList head){//输出链表中各结点的值 LinkList p = head->next; while(p!=NULL){ printf("%s:%d\n",p->word,p->count); p = p->next; } }

    推荐阅读