先前在百度空间里帖了一个函数,很乱也蛮烂的
http://hi.baidu.com/pallove/blog/item/ea3c0b469c4bf0076a63e53e.html
早上使用strstr函数再写了一个,一下感觉清爽多了。
#include <string.h> #include <stdio.h> #include <stdlib.h> char* replace(const char *src, const char *from, const char *to, char *dest) { int idx = 0; char *find; while(1) { if(find = strstr(src, from)) { idx = find - src; strncat(dest, src, idx); strncat(dest, to, strlen(to)); src += idx + strlen(from); } else { strncat(dest, src, strlen(src)); break; } } return dest; } int main() { char *dest = malloc(1024); strcpy(dest, "result:"); printf("%s\n", replace("hello, abcabctestasdlfklasdjabc ldsafabc", "abc", "123", dest)); exit(0); }