简体   繁体   English

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

[英]How to delete special char in C?

There is a string 有一个字符串

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

How to delete all the "#" and return "helloworld" ? 如何删除所有“#”并返回“ helloworld”?

In Ruby I can use gsub to deal with it 在Ruby中,我可以使用gsub处理它

In C, you have to do it yourself. 在C语言中,您必须自己做。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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