我写了这个函数:
void r_tabs_spaces(char *input) {
int i;
for (i = 0; i < strlen(input); i++)
{
if (input[i] == ' ' || input[i] == '\t')
input[i] = '';
}
}
然而,当我编译并运行它时,编译器在我尝试输入 [i] = '' 的行提示“错误:空字符常量”;
那我如何在 C 中执行此操作?
在 C 语言中,字符串是一个字节数组。你不能分配一个“空字节”,但你必须向前移动剩余的字节。
这是一种实现方法:
char *write = str, *read = str;
do {
// Skip space and tab
if (*read != ' ' && *read != '\t')
*(write++) = *read;
} while (*(read++));
请记住,C 中的文字字符串通常位于写保护内存中,因此您必须先复制到堆中才能更改它们。例如,这通常是段错误:
char *str = "hello world!"; // Literal string
str[0] = 'H'; // Segfault
您可以使用 strdup
(以及其他)将字符串复制到堆中:
char *str = strdup("hello world!"); // Copy string to heap
str[0] = 'H'; // Works
编辑:根据您的评论,您可以通过记住您已经看到非空白字符这一事实来仅跳过初始空白。例如:
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++));
我是一名优秀的程序员,十分优秀!