当前位置:文档之家› C语言实现字符串替换函数replace

C语言实现字符串替换函数replace

C语言实现字符串替换函数replace
周常欣2020-1-12
main.c
//############################################################################# #include <stdio.h>
#include <string.h>
#define MAXSTRLEN 2000
//In a string, replaces all occurrences of "oldpiece" with "newpiece".
//把字符串string里所有的“oldpiece(字符串片断)”换成“newpiece(字符串片断)”
//This is not really bulletproof yet.p 这还不是真正防弹的。

char *replace(string, oldpiece, newpiece)
char *string;
char *oldpiece;
char *newpiece;
{
int i, j, limit;
char *c;
char beforestring[MAXSTRLEN], afterstring[MAXSTRLEN];
static char newstring[MAXSTRLEN];
if ((c = (char *) strstr(string, oldpiece)) == NULL)
return string;
limit = c - string;
for (i = 0; i < limit; i++)
beforestring[i] = string[i];
beforestring[i] = '\0';
i += strlen(oldpiece);
for (j = 0; string[i] != '\0'; i++)
afterstring[j++] = string[i];
afterstring[j] = '\0';
sprintf(newstring, "%s%s%s", beforestring, newpiece, afterstring);
while (strstr(newstring, oldpiece))
strcpy(newstring, replace(newstring, oldpiece, newpiece));
return newstring;
}
int main()
{
char *stringok; //字符指针:存放替换后的字符串
char *strings="I love you!"; //字符指针:存放替换前的字符串
char *old_piece="you"; //实参
char *new_piece="China"; //实参
stringok=replace(strings,old_piece,new_piece); //调用替换函数repalce(),实参传形参
printf("替换前的字符串为:%s\n",strings);
printf("替换后的字符串为:%s\n",stringok);
return 0;
}
//############################################################################# VC++6.0编译器调试:。

相关主题