题目
给定文件filein.txt按照要求输出fileout.txt.
输入:无空格的字符串
输出:将filein.txt删除输入的字符串(不区分大小写),输出至fileout.txt。每行中的空格全部提前至行首。
1、KMP匹配
2、不区分大小写地比较
3、子串删除
4、写文件要求(空格提前)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char* filein = "filein.txt";
char* fileout = "fileout.txt";
char* GetFileContent(char* name);
void DeleteSubStr(char* pstr, char* sstr);
void GetNext(char* str, int len, int* next);
bool Equal(char a, char b);
void WriteFile(char* note, char* name);
int main(){
char* note = GetFileContent(filein);
char substr[100];
printf("输入要删除的字符串:");
scanf("%s",&substr);
DeleteSubStr(note,substr);
//printf("%s\n",note);
WriteFile(note,fileout);
return 0;
}
char* GetFileContent(char* name){
FILE* fp;
char* str;
if((fp = fopen(name,"r")) == NULL){
printf("The file %s can not be opened\n",name);
exit(1);
}
int ch;
int size = 0;
while((ch = fgetc(fp)) != EOF)
++size;
rewind(fp);
str = (char* )malloc(sizeof(char) * size + 1);
int i;
for(i = 0; i < size; i++){
ch = fgetc(fp);
str[i] = ch;
}
str[size] = '\0';
fclose(fp);
return str;
}
bool Equal(char a, char b){
if(b>= '0' && b<= '9')
if(a == b)
return true;
if(b>='A' && b<='Z')
if(a == b || a + 'A' - 'a' == b)
return true;
if(b>='a' && b<='z')
if(a == b || a + 'a' - 'A' == b)
return true;
return false;
}
void GetNext(char* str, int len, int* next){
if(len <= 0){
printf("子串大小有误\n");
return ;
}
int i,j;
next[0] = 0;
i = 1;
j = 0;
for(; i < len; ){
if(j == 0 || Equal(str[i - 1],str[j - 1])){
next[i++] = ++j;
}else{
j = next[j - 1];
}
}
}
void DeleteSubStr(char* pstr, char* sstr){
int plen = strlen(pstr);
int slen = strlen(sstr);
int* next = (int* )malloc(sizeof(int) * slen);
GetNext(sstr,slen,next);
int i,j;
//for(i = 0; i < slen; i++)
// printf("%d ",next[i]);
i = j = 0;
while(i < plen && plen >= slen){
if(Equal(pstr[i],sstr[j])){
++i;++j;
if(j == slen){//删除操作
int begin = i - j;
int end = i;
for(; end < plen; end++)
pstr[begin++] = pstr[end];
i -= j;
plen -= j;
j = 0;
}
}else{
if(j == 0)
++i;
else{
j = next[j - 1];
}
}
}
pstr[plen] = '\0';
}
void WriteFile(char* note, char* name){
FILE* fp;
if((fp = fopen(name,"w")) == NULL){
printf("The file %s can not be opened\n", name);
exit(1);
}
int len = strlen(note);
int count = 0;
int begin,end;
int j;
begin = end = 0;
while(begin < len){
while(note[end] != '\n' && end < len){
if(note[end] == ' '){
++count;
}
++end;
}
for(j = 0; j < count; j++){
fputc((int)(' '),fp);
}
for(j = begin; j <= end; j++){
if(note[j] != ' '){
fputc((int)(note[j]), fp);
}
}
++end;
begin = end;
count = 0;
}
fclose(fp);
}
filein.txt:
Who has seen the winD?
Neither I nor you;
But when the leaves hang trembling,
The wInd is passing through.
Who has seen the WIND?
Neither you nor I;
But when the trees bow down their heads,
The Wind is passing by.
–Christina Rossett
输入的子串:
wind
fileout.txt