如何删除C中的特殊字符?

时间:2010-12-28 13:14:11

标签: c linux string

有一个字符串

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

如何删除所有“#”并返回“helloworld”?

在Ruby中,我可以使用gsub来处理它

2 个答案:

答案 0 :(得分:3)

在C中,你必须自己动手。例如:

#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;
}

请注意,在该实现中,调用者必须释放结果字符串。

答案 1 :(得分:1)

我相信有一个更好的算法可以做到这一点....不需要释放 - 它就位。

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;
}
相关问题