119.已有文本文件test.txt,其中的内容为hello,how are you.Welcome you to China!编写一个程序,读取test.txt,统计各单词出现的次数,并将各单词和其出现的次数输出到屏幕和文件中。
仅限一行句子,两行需要稍加修改。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Word //定义单词链表
{
char w[20]; //单词
int count; //该单词出现的次数
struct Word *next;
};
void getData(char str[]) //从文件中逐个读入字符,保存到str字符数组中
{
FILE *fp;
char ch;
int i;
if((fp=fopen("test.txt","r"))==NULL)
{
printf("can't open file!\n");
exit(0);
}
i=0;
while((ch=fgetc(fp))!=EOF)
str[i++]=ch;
str[i]='\0';
fclose(fp);
}
struct Word *Caculate(char str[]) //统计单词及出现的频数
{
int i=0,j=0;
char word1[20]; //找字符串中的每一个单词
struct Word *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'))) //找到了一个单词使j=0
{
word1[j]='\0'; //此时word1中已存放一个单词
/*构造一个单词结构体*/
struct Word *q;
q=(struct Word *)malloc(sizeof(struct Word));
strcpy(q->w,word1);
q->next=NULL;
/*每找到一个单词从表头开始查找,若有此单词,则个数增1;否则将此单词添加进链表*/
struct Word *p=head;
while(p->next!=NULL) //查找
{
if(strcmp(p->next->w,word1)==0)
{
p->next->count++;
break;
}
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);
printf("test.txt数据:%s\n",str);
struct Word *head;
head=Caculate(str);
printf("统计单词及出现的个数:\n");
print(head);
return 0;
}
运行结果:
120.已有文本文件test.txt,其中的内容为Hello,welcome you to Nanjing Normal University!Luck to you! 编写一个程序,读取test.txt,统计各字符出现的次数,并将各字符和其出现的次数输出到屏幕和文件中。
同上题大同小异
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Ch //定义字符链表
{
char ch; //字符
int count; //该字符出现的次数
struct Ch *next;
};
void getData(char str[]) //从文件中逐个读入字符,保存到str字符数组中
{
FILE *fp;
char ch;
int i;
if((fp=fopen("test.txt","r"))==NULL)
{
printf("can't open file!\n");
exit(0);
}
i=0;
while((ch=fgetc(fp))!=EOF)
str[i++]=ch;
str[i]='\0';
fclose(fp);
}
struct Ch *Caculate(char str[]) //统计字符及出现的频数
{
int i;
struct Ch *head=(struct Ch *)malloc(sizeof(struct Ch)); //建立字符空链表
head->next=NULL;
for(i=0; str[i]!='\0'; i++)
{
if((str[i]>='A'&&str[i]<='Z')||(str[i]>='a'&&str[i]<='z')) //找到了一个字符
{
/*构造一个字符结构体*/
struct Ch *q;
q=(struct Ch *)malloc(sizeof(struct Ch));
q->ch=str[i];
q->next=NULL;
/*每找到一个字符从表头开始查找,若有此字符,则个数增1;否则将此字符添加进链表*/
struct Ch *p=head;
while(p->next!=NULL) //查找
{
if(p->next->ch==str[i])
{
p->next->count++;
break;
}
p=p->next;
}
if(p->next==NULL) //链表中无此字符,则插入链表尾
{
p->next=q;
q->count=1;
}
}
}
return head;
}
void print(struct Ch *head)
{
struct Ch *p=head;
while(p->next!=NULL)
{
printf("%c:%d\n",p->next->ch,p->next->count);
p=p->next;
}
}
int main()
{
char str[1000];
getData(str);
printf("test.txt数据:%s\n",str);
struct Ch *head;
head=Caculate(str);
printf("统计字符及出现的个数:\n");
print(head);
return 0;
}
运行结果: