从文件中读取字符,并且统计各单词出现的次数

分三步,首先将字符串从文件中读取出来,然后统计,最后输出到屏幕上。代码如下

//
//  main.cpp
//  11年第7题
//
//  Created by 布布 on 2020/5/10.
//  Copyright © 2020 布布. All rights reserved.
//

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct word{
    char w[20];
    int count;
    struct word *next;
};

void getdata(char str[])
{
    FILE *fp;
    char filename[]="test.txt";
    if ((fp=fopen(filename, "r"))==NULL) {
        printf("can not open file,program exiting\n");
        exit(0);
    }
    char ch=getc(fp);
    int i=0;
    while (ch!=EOF) {
        str[i++]=ch;
        ch=getc(fp);
    }
    str[i]='\0';
    fclose(fp);
}

struct word *caculater(char str[])
{
    char word1[20];
    int i=0,j=0;
    struct word *head;
    head = (struct word *)malloc(sizeof(struct word));
    head->next=NULL;
    for (; str[i]!='\0'; i++) {
        if (!((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))) {
            word1[j]='\0';
            struct word *q;
            q=(struct word *)malloc(sizeof(struct word));
            q->next=NULL;
            strcpy(q->w, word1);
            struct word *p=head;
            while (p->next!=NULL) {
                if (strcmp(p->next->w, q->w)==0) {
                    p->next->count++;
                    break;
                }else{
                    p=p->next;
                }
            }
            if (p->next==NULL) {
                p->next=q;
                q->count=1;
            }
            j=0;
        }else{
            word1[j++]=str[i];
        }
    }
    return head;
}

void print(struct word *head)
{
    struct word *p=head;
    while (p->next!=NULL) {
        printf("%s:%d\n",p->next->w,p->next->count);
        p=p->next;
    }
}



int main()
{
    char str[1000];
    getdata(str);
    puts(str);
    struct word *head;
    head=caculater(str);
    print(head);
    
    
    return 0;
}

参考:https://blog.csdn.net/LY_624/article/details/105158931

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值