开发者

How to delete special char in C?

开发者 https://www.devze.com 2023-02-01 05:21 出处:网络
There is a string char *message = \"hello#world#####.......\"; How to delete all the开发者_C百科 \"#\" and return \"helloworld\" ?

There is a string

char *message = "hello#world#####.......";

How to delete all the开发者_C百科 "#" and return "helloworld" ?

In Ruby I can use gsub to deal with it


In C, you have to do it yourself. For example:

#include <string.h>

char *remove_all(const char *source, char c)
{
    char *result = (char *) malloc(strlen(source) + 1);
    char *r = result;
    while (*source != '\0')
    {
        if (*source != c)
            *r++ = *source;
        source++;
    }

    *r = '\0';
    return result;
}

Note that in that implementation, the caller would have to free the result string.


I believe there is a better algorithm to do this....no freeing is necessary - it's in-place.

char *remove_all(char *string, char c) 
{
   int idx = 0;
   char *beg = string;
   while(*string) {
      if (*string != c) 
         beg[idx++] = *string;
      ++string;
   }
   beg[idx] = 0;

   return beg;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消