字符串替换 您所在的位置:网站首页 java字符串字符替换 字符串替换

字符串替换

#字符串替换| 来源: 网络整理| 查看: 265

字符串替换

写一个字符串替换函数,如母串"123123123123",把母串中的子串"123",替换为"12345",或者"12"。

思路:

利用库函数strstr(),定位子串。使用strcpy()进行替换。不断重复着定位和替换操作,直到定位到NULL为止。

示例代码:

#include #include #include /* 字符串替换 把字符串str中的子串s1,替换成s2 */ char *strReplace(char *str, char *s1, char *s2) { //在堆中申请一片空间 char *s = malloc(50); //清空 memset(s, 0, 50); //把str拷贝到s中 strcpy(s, str); char buf[50]; char *pStr = strstr(s, s1); while (pStr) { //保存后序内容 strcpy(buf, pStr+strlen(s1)); //s2替换s1 strcpy(pStr, s2); //移动pStr pStr += strlen(s2); //把后序内容补上 strcpy(pStr, buf); //寻找下一次替换的位置 pStr = strstr(pStr, s1); } str = s; return str; } void main() { //"123"->"12345" char *str = "123123123123"; printf("原字符串\n"); printf("%s\n", str); str = strReplace(str, "123", "12"); printf("替换后\n"); printf("%s\n", str); free(str); system("pause"); }运行



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有