題目:
假設每行文字長度不超過80個字符,每個單詞由空格分隔,單詞長度不超過20個字符。現在要從鍵盤上輸入一段英文文字,當輸入“stop ”后,結束輸入過程。先編程統計在這段文字中每個單詞出現的個數。
分析:
通過空格判斷單詞,單詞存放在結構體當中,search函數檢測當前單詞是否為重復出現的單詞
cut函數分隔字符串,使其成為單詞
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<stdbool.h> #define MAXSIZE 300 typedef struct node{ char letter[20]; int seq; struct node *next; }Node; bool search(Node **L,char a[])//檢測單詞是否存在 { if((*L)->next==NULL)//如果鏈表當中沒有一個單詞,則默認為當前單詞無重復 return true; Node *p=(*L)->next; while(p!=NULL){//檢測單詞 if(strcmp(p->letter,a)==0) break; else p=p->next; } if(p!=NULL){ ++p->seq; return false;//在鏈表當中查到存在相同的單詞 } else return true;//沒有查到相同的單詞 } void cut(char a[],Node *L) { int n=(int)strlen(a); int i=0;//i在文本中走,j在鏈表中的單詞里走 Node *rear=L; while(i<n) { char temp[20];int j=0; while(a[i]!=' ') temp[j++]=a[i++]; temp[j]='\0';//補全j的最后一位 ++i;//i循環到單詞的后面空格處,跳過空格 if(strcmp(temp,"stop")==0)//遇到stop,函數結束 return; bool is_overlap=search(&L, temp);//確認是否存在於節點當中,傳入L指針的地址 if(is_overlap)//如果單詞無重復,創建一個節點存放當前單詞 { Node *node=(Node *)malloc(sizeof(Node)); strcpy(node->letter, temp); node->seq=1; node->next=NULL; rear->next=node; rear=node; } } } void print(Node *art) { Node *p=art->next; while(p!=NULL){ printf("%s(%d)\t",p->letter,p->seq); p=p->next; } printf("\n"); } int main(){ char a[MAXSIZE]; printf("輸入一串字符,相互之間用空格隔開,結尾以stop\n"); gets(a); int n=(int)strlen(a); if(a[n-1]!=' ') a[n]=' '; a[n+1]='\0'; Node art={"hello",1000}; cut(a, &art); print(&art); }