字符串替换For linux C

本文介绍了一个简单的字符串替换函数实现过程,该函数通过遍历输入字符串并查找需要替换的子串来完成替换操作。使用了基本的C语言字符串处理函数如strstr、memcpy和strcpy等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.临时空间给了个1024,不需要可减少长度。

2.结果只用用strcpy了,没校验。

 

 1 bool Replace(char *str,const char *src, const char *des)
 2 {
 3   /* old -> new */
 4   int srclen = strlen(src);
 5   int deslen = strlen(des);
 6   int siplen = 0;
 7   int buflen = 0;
 8   char *pos = str;
 9   char *ptr = NULL;
10 
11   static char buf[1024];
12 
13   memset(buf, 0x00, 1024);
14   if(strcmp(src,des) == 0)
15     return true;
16     if(strlen(str) < srclen){
17     // The lenth of old word is more then string! 
18     return false;
19   }
20 
21   while((ptr = strstr(pos, src)) != NULL) {
22     siplen = ptr - pos;
23     memcpy(buf + buflen, pos, siplen);
24     strcat(buf, des);
25 
26     buflen += siplen + deslen;
27     pos = pos + siplen + srclen;
28   }
29 
30   if (buflen != 0) {
31     strcpy(buf + buflen, pos);
32     strcpy(str, buf);
33   }
34 
35   return true;
36 }

 

转载于:https://www.cnblogs.com/sciapex/p/6441751.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值