#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define N 20
typedef struct ch {
char a[20];
int num;
struct ch* next;
}Ch;
struct ch* tongji(char[], Ch*);
void printc(Ch*);
int main()
{
FILE* fp;
char a[N];
int i = 0,j;
if ((fp = fopen("D:\\c\\test.txt", "r")) == NULL)
{
printf("cannot open this file");
exit(0);
}
Ch* p, * q;
q = p = (Ch*)malloc(sizeof(Ch));
if (!p)
exit(0);
p->next = NULL;
while (fscanf(fp,"%s",a)!=EOF)
{
q=tongji(a,p);
}
printc(q);
return 0;
}
Ch* tongji(char a[], Ch*head) {
int i = 0,j=strlen(a);
Ch* p, * q;
if(!isalpha(a[j-1]))
a[j]='\0';
p = head;
while (p->next)
{
if (strcmp(p->next->a,a)==0)
{
p->next->num++;
break;
}
else
p = p->next;
}
if (p->next == NULL)
{
q = (Ch*)malloc(sizeof(Ch));
if (!q)
exit(0);
p->next = q;
strcpy(q->a, a);
q->next = NULL;
q->num = 1;
}
return head;
}
void printc(Ch* head)
{
Ch* p = head;
while (p->next)
{
printf("%5s %5d\n", p->next->a, p->next->num);
p = p->next;
}
}
统计文件字符串中单词出现的次数
最新推荐文章于 2025-03-24 18:36:36 发布