c实现replace功能

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * 功能说明:计算原数据中有多少目的字符串 
 * 参数说明:original_data,	待替换的原始数据 
 * 			 key,			目的字符串
 * 返回数值:原数据中待替换字符串的个数 
 */
int string_count(char *original_data, char *key)
{
	int count = 0;
	int key_len = strlen (key);
	char *pos_start = original_data, *pos_end = NULL;

	while (NULL != 
		   (pos_end = strstr (pos_start, key)))
	{
		pos_start = pos_end + key_len;
		count++;
	}

	return count;
}

/*
 * 功能说明:replace功能
 * 参数说明:original_data, 	待替换的原始数据 
 * 			 replaced,			被替换的字符串
 * 			 to,				替换成的字符串
 * 返回数值:成功,新字符串的地址
 * 			 失败,NULL
 */
char *replace(char *original_data, char *replaced, char *to)
{
	int rep_len = strlen (replaced);
	int to_len = strlen (to);
 	int counts = string_count (original_data, replaced);
	int m = strlen(original_data) + counts * (to_len - rep_len);/* 计算将要分配的内存的大小 */
	char *new_buf = NULL;
		
	new_buf = (char *) malloc (m + 1);
	if (NULL == new_buf)
	{
		printf ("malloc error\n");
		return NULL;
	}

	memset (new_buf, 0, m + 1);

	char *pos_start = original_data, *pos_end = NULL, *pbuf = new_buf;
	int copy_len = 0;

	while (NULL != (pos_end = strstr (pos_start, replaced)))
	{
		copy_len = pos_end - pos_start;		/* 计算好要拷贝的长度:要替换的字符串之前的字符长度 */
		strncpy (pbuf, pos_start, copy_len);/* 拷贝到新分配的内存区 */
		pbuf += copy_len;					/* 新内存区的指针往后移,等待下一次内容的写入 */
		strncpy (pbuf, to, strlen(to));     /* 将希望替换的字符串接到后面 */
		pbuf += to_len;						/* 新内存区的指针往后移,等待下一次内容的写入 */
		pos_start = pos_end + rep_len;		/* 越过被替换的字符串,继续后面的替换 */
	}
	strncpy (pbuf, pos_start, strlen(pos_start) + 1);/* 拷贝最后一个匹配的字符串后面的字符串(顺带拷贝'\0') */

	return new_buf;
}

int main(int argc, const char *argv[])
{
	char buf[] = "dfdshrplease, don'tdngljljeplease, don'tjlsdjf";
	char *replaced = "please, don't";
	char *to = "哇哈哈";
	char *result = NULL;
	
	printf ("%s\n", buf);
	
	result = replace (buf, replaced, to);
	if (NULL != result)
	{
		printf ("%s\n", result);
	}

	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值