- 论坛徽章:
- 1
|
大家有没有用C写过替换字符串的函数?
我刚写了一个:
- #include <stdio.h>;
- #include <string.h>;
- #include <stdlib.h>;
- char *str_replace(char string[] ,char old[] ,char new[] ,int lenth)
- {
- char *ret,*here;
- int n;
- if((here=strstr(string,old))==NULL)
- return NULL;
- ret=(char *)malloc(sizeof(char)*lenth);
- n=strlen(string)-strlen(here);
- memcpy(ret,string,n);
- memcpy(ret+n,new,strlen(new));
- memcpy(ret+n+strlen(new),here+strlen(old),strlen(here)-strlen(old));
- return ret;
- }
- int main()
- {
- printf("%s\n",str_replace("abcd1234efg","1234","654321",20));//长度大于替换的串.
- printf("%s\n",str_replace("abcd1234efg","1234","xyz",20));//长度小于替换的串.
- printf("%s\n",str_replace("abcd1234efg","1234","wxyz",20));//长度等于替换的串.
- return 0;
- }
复制代码
- [root@Reinnat tmp]# ./097
- abcd654321efg
- abcdxyzefg
- abcdwxyzefg
复制代码
全都替换成功了.
函数里有个lenth.这需要程序员自己把握.最终的字符串有多长.否则发生不可预料的事 只能赖程序员自己了. |
|