Skip to content

Instantly share code, notes, and snippets.

@sokrato
Created November 10, 2013 13:40
Show Gist options
  • Save sokrato/7398400 to your computer and use it in GitHub Desktop.
Save sokrato/7398400 to your computer and use it in GitHub Desktop.
word counting program in C
#include<stdio.h>
#include<string.h>
#include<ctype.h>
struct node{
int num;
char *p;
struct node *next;
};
int main(int argv,char *argc[]){
FILE *fp;
char str[1000];
if((fp=fopen("test.c","rt"))==NULL){
printf("Canot open file strike any key to exit!");
getchar();
exit(1);}
fread(str,4,1000,fp);
fclose(fp);
int i;
char *str1=str;
//¶ÁÊýŸÝÓöµœœáÊø·ûÌáÇ°œáÊø£¬œÚÊ¡ÄÚŽæ¿ÕŒä
for(i=0;i<1000;i++){
if(str[i]=='\0')
break;}
i=0;
//tap ŒÇŒǰһ×Ö·û׎̬£¬1Ϊ·Ç×ÖÄž£¬2Ϊ×ÖÄž;
int tab=1;
char *temp=str1;
//º¯ÊýÉùÃ÷
struct node*Add();
struct node*Head=NULL;
while(str[i]!='\0'){
if((isalpha(str[i])==0)&&(tab==1)){
str[i]='\0';
i++;
str1++;
tab=1;}
else if((isalpha(str[i])==0)&&(tab==2)){
str[i]='\0';
i++;
Head=Add(Head,temp);
str1++;
tab=1;}
else if((isalpha(str[i])!=0)&&(tab==1)){
temp=str1;
i++;
tab=2;
str1++;}
else if((isalpha(str[i])!=0)&&(tab==2)){
i++;
tab=2;
str1++;}}
printf("The words data:\n");
struct node* temp1=Head;
while(temp1!=NULL){
printf("Word(s):%s\t,Number:%d\n",temp1->p,temp1-> num);
temp1=temp1->next;}
return(0);
}
struct node* Add(head,word)
struct node* head;
char* word;{
struct node *p1,*p2;
p1=(struct node*) malloc(sizeof(struct node));
p1->num=1;
p1->p=word;
p2=head;
if(head==NULL){
head=p1;
p1->next=NULL;
return(head);}
while(p2->next!=NULL){
if(strcmp(p2->p,p1->p)==0){
p2->num++;
return(head);}
p2=p2->next;}
if(strcmp(p2->p,p1->p)==0){
p2->num++;
return(head);}
p2->next=p1;
p1->next=NULL;
return(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment