思路:主要是利用strstr()函数找到那个位置,然后利用strcat拼接三部分。
自己需要注意的:scanf后再用其他输入函数时,注意弃置换行符。(好久没写都忘了。。)strncpy将源字符串的前n位拷过来后不会自动加'\0'
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void edit(int n);
char fstr[10][90];
char rstr[10][90];
char text[256];
char tempt[256];
int main()
{
int n,i;
while(scanf("%d",&n)&&n)
{
i=0;
memset(fstr,0,sizeof(fstr));
memset(rstr,0,sizeof(rstr));
memset(text,0,sizeof(text));
memset(tempt,0,sizeof(tempt));
getchar();//弃置换行符
while(i<n)
{
gets(fstr[i]);
gets(rstr[i++]);//这里不能用scanf输入,用fgets的话会有回车符存入。另外,上一行不要i++。。。
}
gets(text);
//puts(fstr[i-1]);puts(rstr[i-1]);puts(text);
edit(n);
}//while
//system("pause");
return 0;
}
void edit(int n)
{
char* str=NULL;
for(int i=0;i<n;++i)
{//遍历每个fstr,即使用每条规则
while(str=strstr(text,fstr[i]))
{
//printf("str:%s\n",str);
strncpy(tempt,text,strlen(text)-strlen(str));
*(tempt+strlen(text)-strlen(str))='\0';//strncpy拷过来n个字符后不会自动加'\0'!!!或者在循环的最后把tempt初始化为空。。
//printf("t:%s\nf:%s\ntempt:%s\nr:%s\n",text,fstr[i],tempt,rstr[i]);
strcat(tempt,rstr[i]);
strcat(tempt,str+strlen(fstr[i]));
strcpy(text,tempt);
}
}
puts(text);
}