在 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++));