#define _CRT_SECURE_NO_WARNINGS
#include<string>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
/*
src:原字符串
dst:生成的或者需要填充的字符串
sub:需要查找的子字符串
new_sub:提换的新子字符串
return :0 成功
:-1 失败
*/
int replacesubstr(/*in*/ char *src,/*out*/ char **dst,/*in*/char *sub,/*in*/ char *new_sub)
{
char *start = src;
char *p=NULL;
char tem[512] = { 0 };
int n;
if (start == NULL&&dst == NULL&&sub == NULL&&new_sub == NULL)
{
return -1;
}
do
{
p = strstr(start,sub);
if (p != NULL)
{
n = 0;
n = p - start;
if (n > 0)
{
strncat(tem, start, n);
}
strncat(tem, new_sub, strlen(new_sub));
start = p + strlen(sub);
}
else
{
strcat(tem,start);
break ;
}
} while (*start!=0);
char *buf = (char *)malloc(strlen(tem) + 1);
strcpy(buf, tem);
*dst = buf;
return 0;
}
int main(void)
{
int ret;
char *src = "abcd11111abcd2222abcdqqqq";
char *dst = NULL;
char *sub = "abcd";
char *new_sub = "dcba";
ret = replacesubstr(src,&dst,sub,new_sub);
if (ret != 0)
{
printf("ret:err%d", ret);
}
printf("%s", dst);
if (dst!=NULL)
{
free(dst);
dst = NULL;
}
system("pause");
}
字符串的替换(如abcd1122abcd替换成daba1122daba)
最新推荐文章于 2024-11-14 19:11:37 发布