#include
#include
#include
// 字符串替换(源字符串, 旧字符串, 新字符串)
char *replace(const char *str, const char *str1, const char *str2)
{
char *pstr1, *pstr2, *pbuf1, *pbuf2;
char ch;
pbuf1 = NULL;
pbuf2 = NULL;
pstr1 = strstr(str, str1);
while (pstr1 != NULL) {
ch = *pstr1;
*pstr1 = 0;
if (pbuf1 == NULL) {
pbuf1 = (char *)malloc(strlen(str) + strlen(str2) + 1);
pbuf1[0] = 0;
} else {
pbuf2 = (char *)malloc(strlen(pbuf1) + strlen(str) + strlen(str2) + 1);
strcpy(pbuf2, pbuf1);
free(pbuf1);
pbuf1 = pbuf2;
}
strcat(pbuf1, str);
strcat(pbuf1, str2);
*pstr1 = ch;
str = pstr1 + strlen(str1);
pstr1 = strstr(str, str1);
}
if (str && str[0]) {
if (pbuf1 == NULL) {
pbuf1 = (char *)malloc(strlen(str) + strlen(str2) + 1);
pbuf1[0] = 0;
} else {
pbuf2 = (char *)malloc(strlen(pbuf1) + strlen(str) + strlen(str2) + 1);
strcpy(pbuf2, pbuf1);
free(pbuf1);
pbuf1 = pbuf2;
}
strcat(pbuf1, str);
}
return pbuf1;
}
main()
{
char str[] = "111\n2222\n333";
char *an;
printf("%s\n\n", str);
an = replace(str, "\n2222\n", "");
printf("%s\n", an);
}
阅读(2565) | 评论(0) | 转发(0) |