编译环境:VS2010。
语言: C。
代码:
#include <stdlib.h> #include <stdio.h> #include <string.h> void str_replace(char *str_src, int n, char * str_copy); void main(void) { char str_source[50] = "the book the source the end!\n"; char str_find[10] = "the"; char str_to_copy[10] = "+++"; char *p; printf("%s", str_source); p = strstr(str_source, str_find); while(p){ str_replace(p, strlen(str_find), str_to_copy); p = p + strlen(str_to_copy); p = strstr(p, str_find); } printf("%s", str_source); } void str_replace(char *str_src, int n, char * str_copy) { int lenofstr; int i; char *tmp; lenofstr = strlen(str_copy); //string to copy is shorter than string to find if(lenofstr < n) { tmp = str_src+n; while(*tmp) { *(tmp-(n-lenofstr)) = *tmp; //n-lenofstr, length of moving tmp++; } *(tmp-(n-lenofstr)) = *tmp; //move '\0' } else if(lenofstr > n) //string to copy longer than string to find { tmp = str_src; while(*tmp) tmp++; while( tmp>=(str_src+n) ) { *(tmp+(lenofstr-n)) = *tmp; tmp--; } } strncpy(str_src, str_copy, lenofstr); }
测试结果:
查找字符串和替换字符串 长度相等
查找字符串的长度 小于 替换字符串的长度
查找字符串的长度 大于 替换字符串的长度