回复 13楼 九转星河
感觉strstr好用点
/*
在s1中搜索s2并用s3替换每次出现的s2
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strtran(char *s1, char *s2, char *s3)
{
if (!*s1 || !*s2 || !*s3)
return s1;
int len1=strlen(s1);
int len2=strlen(s2);
int len3=strlen(s3);
if (len1 < len2)
return s1;
int len, bufsize=1;
char *buf=(char*)calloc(bufsize, sizeof(char));
char *p1=s1, *p2;
for (p2=strstr(s1,s2); p2; p2=strstr(p2,s2))
{
len = p2 - p1;
buf = (char*)realloc(buf, (bufsize+len+len3)*sizeof(char));
strncpy(buf+bufsize-1, p1, len);
strcpy(buf+bufsize+len-1, s3);
bufsize += len + len3;
p2 += len2;
p1 = p2;
}
len = strlen(p1);
buf = (char*)realloc(buf, (bufsize+len)*sizeof(char));
strcpy(buf+bufsize-1, p1);
return buf;
}
main()
{
char s1[256], s2[256], s3[256];
while (1)
{
printf("s1: ");
gets(s1);
printf("s2: ");
gets(s2);
printf("s3: ");
gets(s3);
if (!*s1 || !*s2 || !*s3)
break;
char *s = strtran(s1, s2, s3);
puts(s);
free(s);
}
}