简体   繁体   中英

How to delete special char in C?

There is a string

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

How to delete all the "#" 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM