博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
字符串中子串替换成新子串 简单实现
阅读量:3523 次
发布时间:2019-05-20

本文共 1094 字,大约阅读时间需要 3 分钟。

#include 
#include
#include
/* * 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);}

转载地址:http://zxuhj.baihongyu.com/

你可能感兴趣的文章
SQL 约束(二)
查看>>
SQL ALTER用法(三)
查看>>
SQL where子句及查询条件语句(六)
查看>>
SQL 连接JOIN(九)
查看>>
linux VM虚拟机可以ping通主机,但主机无法ping通虚拟机
查看>>
linux 错误码
查看>>
C++ 中Struct与typedef struct总结
查看>>
WNetAddConnection2调用失败,错误码1200/1312
查看>>
POI读写Excel的基本使用
查看>>
淘宝网站的架构演进
查看>>
设置zookeeper开机自启动流程
查看>>
CentOS安装mysql5.7的教详细流程
查看>>
项目整合微信扫码登录功能
查看>>
分布式文件系统FastDfs的搭建
查看>>
Springboot项目利用Java客户端调用FastDFS
查看>>
全文检索工具elasticsearch的安装和简单介绍
查看>>
利用Kibana学习全文检索工具elasticsearch
查看>>
SpringBoot在Test测试类或自定义类中通过@Autowired注入为null
查看>>
使用docker搭建YAPI服务
查看>>
西南科技大学OJ题 邻接表到邻接矩阵1056
查看>>