c - 如何在C中合并文本中的所有可能空格
问题描述
该函数的目的是将字符串中所有可能的空格合并到一个空格中。我编写的代码可以正常工作,但有一个字符串会中断。
void merge_whitespace(char *str) {
char *d = str;
while(*str != '\0') {
while (*str == '\t' || *str == '\r' || *str == '\n' || *str =='\f' || *str =='\v' || (*str == ' ' && *(str+1) == ' ')) {
str++;
}
*d++ = *str++;
}
*d = '\0';
}
test
[This is another test. Now we
have all kinds of white space ]
My output is:
[This is another test. Now we have all kinds of white space ]
but should be:
[This is another test. Now we have all kinds of white space ]
So the problem is in the string test, it prints two spaces instead of one.
解决方案
文字就像
" \n "
因此,当遇到第一个空格时,它会检查
(*str == ' ' && *(str+1) == ' ')
str 确实等于 ' ',但 str+1 等于 '\n',而不是 ' '。所以,这就是它失败的方式。