C语言数据结构 统计英文文字每个“单词”出现次数

题目:

假设每行文字长度不超过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]='';//补全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)	",p->letter,p->seq);
        p=p->next;
    }
    printf("
");
}
int main(){
    char a[MAXSIZE];
    printf("输入一串字符,相互之间用空格隔开,结尾以stop
");
    gets(a);
    int n=(int)strlen(a);
    if(a[n-1]!=' ')
        a[n]=' ';
    a[n+1]='';
    Node art={"hello",1000};
    cut(a, &art);
    print(&art);
}
原文地址:https://www.cnblogs.com/oldfish123/p/13661380.html