编写函数DelStr(str1,str2)。其中str1和str2为两个字符串。函数的功能是从str1中删除所有str2字串,结果由str1输出。函数没有返回值。例如,输入str1为“howareyouareGGGare”,str2为“are”,那么调用函数DelStr(str1,str2)后str1为“howyouGGG”
字符串基本功练手代码。codepad.org已验证。
一个比较复杂的字符串函数,从思考到完成25分钟左右。虽然代码写的傻但是一次无bug过。值得撒花,几个月来没有白练。
- #include <string.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define SWAP(a,b) a^=b;b^=a;a^=b
- char* mydelstr(char* src, const char* del){
- if(src == NULL || !*src|| del==NULL || !*del) return src;
- char* ret = src;
- int dellen = strlen(del);
- int srclen = strlen(src);
- char* pEmpty = NULL;
- char* pChar = NULL;
- //replace the target with \0
- while( (src = strstr(src, del))!=NULL){
- int i = 0;
- if(pEmpty == NULL)
- pEmpty = src;
- for(;i<dellen; i++)
- src[i]='\0';
- src+=dellen;
- if(pChar == NULL)
- pChar = src;
- }
- //re-orgnize
- int i = 0;
- while(pEmpty!=NULL && pChar!=NULL && *pChar){
- SWAP(*pEmpty, *pChar);
- while(*pEmpty!='\0') pEmpty++;
- while(*pChar=='\0' && pChar<ret+srclen) pChar++;
- if(pChar == ret+srclen)
- break;
- }
- return ret;
- }
- int main(){
- char src1[] = "abcdbce";
- char* del1 = "bc";
- char src2[] = "abc";
- char src3[] = "a";
- char src4[] = "bc";
-
- printf("case 1:%s \n", mydelstr(src1, del1));
- printf("case 2:%s \n", mydelstr(src2, del1));
- printf("case 3:%s \n", mydelstr(src3, del1));
- printf("case 4:%s \n", mydelstr(src4, del1));
- printf("------------end----------");
- }
阅读(1109) | 评论(0) | 转发(1) |