#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* parameter:
* src:输入参数,要替换的字符串
* oldSub:src中将要被替换的子串
* newSub:替换成此串
* output:输出结果
* */
char* replace(const char* src,const char* oldSub,const char* newSub,char* output)
{
char* pOutput = output;
const char* pSrc = src;
int len_oldSub = strlen(oldSub);
int len_newSub = strlen(newSub);
/*
* 遍历源字符串
* */
while(*pSrc)
{
/*
* 在源字符串中找到老的子串的位置
* */
pSrc = strstr(pSrc,oldSub);
/*
* 如果找到有结果
* */
if(pSrc != NULL)
{
/*
*把子串前 的部分拷贝到要输出的空间中
*为了跳过老的子串
* */
memcpy(pOutput,src,pSrc - src);
/*
* 把pOutput 移动到末位
* 目的是为了下一次从这里开始继续拷贝
* */
pOutput += pSrc - src;
/*
* 把新字符替换进来
* */
memcpy(pOutput,newSub,len_newSub);
pOutput += len_newSub;
/*
*为了下一个要替换的子串做准备
* */
pSrc += len_oldSub;
src = pSrc;
}
/*
* 否则找不到子串
* */
else
{
break;
}
}
*pOutput = '\0';
/*
* 复制src中最后剩余的部分
* */
if(*src != '\0')
strcpy(pOutput,src);
return output;
}
int main(int argc,char** argv)
{
char *res = (char*)malloc(1024);
res = replace(argv[1],argv[2],argv[3],res);
printf("res = %s\n",res);
free(res);
}
字符串中子串替换成新子串 简单实现
最新推荐文章于 2023-12-01 23:20:15 发布