gpt4 book ai didi

c - 如何在 C 中用空字符替换空格和制表符?

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:45 24 4
gpt4 key购买 nike

我写了这个函数:

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

关于c - 如何在 C 中用空字符替换空格和制表符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1735050/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com