如何用C中的任何内容替换空格和制表符?

goe*_*goe 0 c tabs replace spaces

我写了这个函数:

void r_tabs_spaces(char *input) {
       int  i;
       for (i = 0; i < strlen(input); i++)
       {
        if (input[i] == ' ' || input[i] == '\t')
                    input[i] = '';
       }
}
Run Code Online (Sandbox Code Playgroud)

但是当我编译并运行它时,编译器在我尝试输入[i] =''的行中抱怨"错误:空字符常量";

那怎么能用C做呢?

And*_*mar 8

在C中,字符串是一个字节数组.您不能指定"空字节",但必须将剩余的字节向前移动.

这是如何做到这一点的一种方式:

char *write = str, *read = str;
do {
   // Skip space and tab
   if (*read != ' ' && *read != '\t')
       *(write++) = *read;
} while (*(read++));
Run Code Online (Sandbox Code Playgroud)

请记住,C中的文字字符串通常位于写保护的内存中,因此您必须先复制到堆中,然后才能更改它们.例如,这通常是段错误:

char *str = "hello world!"; // Literal string
str[0] = 'H'; // Segfault
Run Code Online (Sandbox Code Playgroud)

您可以使用strdup(以及其他)将字符串复制到堆中:

char *str = strdup("hello world!"); // Copy string to heap
str[0] = 'H'; // Works
Run Code Online (Sandbox Code Playgroud)

编辑:根据您的评论,您可以通过记住您已经看到非空白字符的事实来跳过初始空白.例如:

char *write = str, *read = str;
do {
   // Skip space and tab if we haven't copied anything yet
   if (write != str || (*read != ' ' && *read != '\t')) {       
       *(write++) = *read;
   }
} while (*(read++));
Run Code Online (Sandbox Code Playgroud)