c 查找替换字符串
#include <stdio.h> #include <string.h> char *mystrstr(char *s1, char *s2) { int i; if (*s2) { while(*s1) { for(i = 0; *(s1+i) == *(s2+i); i++) { if(!*(s2+i+1)) return (char *)s1; } s1++; } return NULL; } else { return (char*)s1; } } void fun(char *str, char *temp,char *substr1, char *substr2) { int len,len1,len2; len1 = strlen(substr1); len2 = strlen(substr2); char *p_str = str; //字符串中第一次出现替换串的位置,并返回指针(找不到则返回null). char *p = mystrstr(str, substr1); if(p) { while(p) { //被替换串前边字符串的长度. len = (int)(p - p_str); //复制到输出字符串. memcpy(temp, p_str, len); memcpy(temp+len, substr2 , len2); //跳过被替换串. p_str = p + len1; //移动到最后 temp = temp + len + len2; //重新查找 p = strstr(p_str, substr1); } //拷贝剩余 strcpy(temp, p_str); } else { strcpy(temp, p_str); } } int main(int argc, char *argv[]) { printf("Hello, world\n"); char str[][30] = {"abcedfrbcxybc","abcedfrbceybce"}; char sub1[][10] = {"bc", "bce"}; char sub2[][10] = {"ghi", "gh"}; char temp[30] = ""; int i; for(i = 0; i < 2; i++) { memset(temp,0,30); printf("str--->%s\n",str[i]); printf("sub1--->%s\n",sub1[i]); printf("sub2--->%s\n",sub2[i]); fun(str[i], temp, sub1[i], sub2[i]); printf("%s, len:%d\n",temp, strlen(temp)); } return 0; }