#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;
}
c实现replace功能
最新推荐文章于 2023-12-23 11:22:50 发布