【发布时间】:2018-01-27 11:43:42
【问题描述】:
函数 TrimRight 取一行并删除末尾的所有空格。
void TrimRight(char *s) // input "somestring " (3 spaces at the end)
{
// Here s == "somestring \0" and strlen(s) == 14
int last = strlen(s) - 2;
std::cout << "Last1: " << s[last] << std::endl; // Last == ' '
while (s[last] == ' ')
{
--last;
}
std::cout << "Last2: " << s[last] << std::endl; // Last == 'g'
s[last + 1] = '\0';
// Here s == "somestring" and strlen(s) == 10
}
问题是为什么 s!= "somestring/0" 在 TrimRight(s) 之后? 我正在使用 MVS 2017。谢谢。
【问题讨论】:
-
如果
s是"somestring "(有3个空格),那么strlen(s)不是14。 -
字符串终止符(
'\0')不计入strlen()。 -
你的函数在字符串长于
INT_MAX+2、字符串短于 2 以及仅由空格组成的字符串上被破坏。如果字符串中的最后一个字符不是空格,也会产生错误的结果。 -
C++有一个字符串类,用它吧。