/* 實現:刪除重復單詞
從同目錄下讀入文本 wordin.txt ,進行處理,輸出到 wordout.txt
*/
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int delCword(char *temp,char *newstr) //temp 為原字符串,newstr 為處理後的字符串
{ //#include<stdlib.h> #include<windows.h> //需要頭文件 存在隱患:未檢測newstr的大小
typedef struct Mystr
{ char *str;
Mystr *next;
}mystr;
char last[100]="",chlast;
int n=0,k=0,flag=1;
Mystr *head=NULL,*st,*delpt,*lastpt;
newstr[0]='\0';
do
{ chlast=*temp++;
//從第壹個字母開始保存於last中,遇到非字母則得到壹個單詞
if(isalpha(chlast) || isalnum(chlast) || '-'==chlast)
{ last[k++]=chlast; last[k]='\0'; }
else { st=head;
while(st)
{ if(!strcmp(st->str,last)) { flag=0;break; }//與現存單詞比較
st=st->next;
}
if(1==flag && k>0) //沒有重復的則存於鏈表中
{ Mystr *pt=(Mystr *)malloc(sizeof(Mystr));
pt->str=(char *)malloc(sizeof(char)*(k+1));
pt->next=NULL;
strcpy(pt->str,last);
if(0==n) lastpt=head=pt;
else { lastpt->next=pt; lastpt=pt; }
n++;
}
flag=1; // 重設標誌位,默認為與現存字符串不重復
k=0;
}
}while(chlast);
st=head;
while(st) //復制到字符串
{ strncat(newstr,st->str,strlen(st->str)); strncat(newstr," ",1);
st=st->next;
}
st=head;
while(st) //清理垃圾
{ delpt=st->next; free(st->str); free(st);
st=delpt;
}
return n;
}
void main()
{ char *s2,*s3,ch;
FILE *fp;
int i=0;
if((fp=fopen("wordin.txt","r"))!=NULL) //從文本輸入
{ fseek(fp,0,SEEK_SET);
fseek(fp,0,SEEK_END);
int longBytes=ftell(fp);// 得到文件長度
fseek(fp,0,SEEK_SET);
s3=(char *)malloc(sizeof(char)*(longBytes+1));
s2=(char *)malloc(sizeof(char)*(longBytes+1));
//fread(s3,longBytes,1,fp);
i=0;
while((ch=fgetc(fp))!=EOF)
s3[i++]=ch;
s3[i]='\0';
}
fclose(fp);
printf("\n元字符串:%s\n",s3);
printf("%d :\n%s",delCword(s3,s2),s2); //調用函數刪除重復單詞,並輸出結果
if((fp=fopen("wordout.txt","w+"))!=NULL) //輸出到文本
fwrite(s2,strlen(s2),1,fp);
fclose(fp);
printf("\n");
free(s2);
free(s3);
}