c语言编程之字符串操作


1. //在s串中查找与s1相匹配的字符串,找到后用s2将s中与s1相配的串替换掉
2. #include<stdio.h>
3. #include<string.h>
4.
5. void replace(char *s,char *s1,char *s2);
6.
7. int main(int argc,char *argv[])
8. {
9. char s[256],s1[256],s2[256];
10.
11. if(argc!=4)
12. {
13. printf("Usage:%s 源串 查找串 替换串\n",argv[0]);
14. exit(-1);
15. }
16.
17. memset(s,sizeof(s),0x00);
18. memset(s1,sizeof(s1),0x00);
19. memset(s2,sizeof(s2),0x00);
20.
21. strcpy(s,argv[1]);
22. strcpy(s1,argv[2]);
23. strcpy(s2,argv[3]);
24.
25. replace(s,s1,s2);
26. printf("%s\n",s);
27. }
28.
29. void replace(char *s,char *s1,char *s2)
30. {
31. char *p,*sp,*dp;
32. int len,cnt;
33.
34. for(;;)
35. {
36. if((p=strstr(s,s1)) == NULL) return;
37.
38. len = strlen(s2)-strlen(s1);
39. if(len)
40. {
41. //查找串和替换串长度不相同,需移位动作
42. sp=p+strlen(s1); //从sp所指位置移
43. dp=sp + len; //移到dp所指位置
44. cnt = strlen(sp) + 1; //所要移动的长度
45. memmove(p+strlen(s1)+len,p+strlen(s1),cnt);
46. }
47. memcpy(p,s2,strlen(s2));
48. }
49. }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值