#include<stdio.h> #include<string.h> void replace(char str[],char key[],char swap[]) { int l1,l2,l3; int i,j; int flag; char tmp[1000]; l1=strlen(str); l2=strlen(key); l3=strlen(swap); for(i=0;i<=l1-l2;i++) { flag=1; for(j=0;j<l2;j++)//注意是小写的l而不是数字1 { if(str[i+j]!=key[j]) { flag=0; break; } } if(flag) { strcpy(tmp,str); strcpy(&tmp[i],swap); strcpy(&tmp[i+l3],&str[i+l2]); strcpy(str,tmp); i+=l3-1; l1=strlen(str); } } } int main() { char str[] ="I have a dream"; char key[] ="have"; char swap[]="Love"; printf("原字符串是%s\n被替换的子串%s,替换为%s\n",str,key,swap); replace(str,key,swap); puts("替换后的字符串是:"); puts(str); return 0; }
原文地址:http://blog.csdn.net/u012110719/article/details/41251987