如何在 C 中将空格和制表符替换为空?
我写了这个函数:
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中做到这一点呢?
I wrote this function:
void r_tabs_spaces(char *input) {
int i;
for (i = 0; i < strlen(input); i++)
{
if (input[i] == ' ' || input[i] == '\t')
input[i] = '';
}
}
However when I compile this and run it, the compiler complains that "error: empty character constant" at line where I try to input[i] = '';
How can I do this in C then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C 语言中,字符串是字节数组。您不能分配“空字节”,但必须将其余字节向前移动。
以下是实现此目的的一种方法:
请记住,C 中的文字字符串通常位于写保护内存中,因此您必须先将其复制到堆中,然后才能更改它们。例如,这通常会出现段错误:
您可以使用
strdup
(以及其他)将字符串复制到堆:编辑:根据您的评论,您可以通过记住您已经看到的事实来仅跳过初始空白非空白字符。例如:
In C, a string is an array of bytes. You can't assign an "empty byte", but you have to shift the remainder of the bytes forward.
Here's one way of how to do that:
Remember that literal strings in C are usually in write-protected memory, so you have to copy to the heap before you can change them. For example, this usually segfaults:
You can copy a string to the heap with
strdup
(among others):EDIT: Per your comment, you can skip only initial whitespace by remembering the fact that you've seen a non-whitespace character. For example:
如果你有一个指向字符串的指针,
只需移动它......
例如:
If you have a pointer to the string
just move it ...
for example:
删除字符串中的一个字符的方法是将字符串的其余部分向后移动一个字符。
The way to remove a character of a string is to move the rest of the string one character back.
用于
将指针
foo
移动到第一个不是空格或制表符的字符。要实际从动态分配的字符串中删除字符,请使用
Use
to move the pointer
foo
to the first character which is not a space or tab.To actually remove the characters from a dynamically allocated string, use