【问题标题】:Why is the line end character not included in the char*?为什么 char* 中不包含行尾字符?
【发布时间】: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++有一个字符串类,用它吧。

标签: c++ char c-strings


【解决方案1】:

你想在TrimRight(s)之后,变成something\0

但在TrimRight(s) 函数中,while loop 只是从最后一个索引传递过来的。

通过意味着它没有删除whitespace\0

所以 s 不是something\0。是something\0 \0,因为“刚刚通过”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多