首页 > 其他 > 详细

字符串替换

时间:2014-09-17 01:12:21      阅读:271      评论:0      收藏:0      [点我收藏+]

                              字符串替换

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

思路:

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


示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
字符串替换
把字符串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");
}
运行

bubuko.com,布布扣

bubuko.com,布布扣




字符串替换

原文:http://blog.csdn.net/zhangxiangdavaid/article/details/39326609

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!