【问题标题】:Remove extra whitespace from c++ issue从 C++ 问题中删除多余的空格
【发布时间】:2021-02-11 07:58:49
【问题描述】:

我有这个来自网上的代码 sn-p。


    void ShortenSpace(string &s)
    {
        // n is length of the original string
        int n = s.length();
     
        //pointer i to keep trackof next position and j to traverse
        int i = 0, j = -1;
     
        // flag that sets to true is space is found
        bool spaceFound = false;
     
        // Handles leading spaces
        while (++j < n && s[j] == ' ');
     
        // read all characters of original string
        while (j < n)
        {
            // if current characters is non-space
            if (s[j] != ' ')
            {
                //if any preceeding space before ,.and ?
                if ((s[j] == '.' || s[j] == ',' ||
                     s[j] == '?') && i - 1 >= 0 &&
                     s[i - 1] == ' ')
                    s[i - 1] = s[j++];
     
                else
                    // copy current character to index i
                    // and increment both i and j
                    s[i++] = s[j++];
     
                // set space flag to false when any
                // non-space character is found
                spaceFound = false;
            }
            // if current character is a space
            else if (s[j++] == ' ')
            {
                // If space is seen first time after a word
                if (!spaceFound)
                {
                    s[i++] = ' ';
                    spaceFound = true;
                }
            }
        }
     
        // Remove trailing spaces
        if (i <= 1)
            s.erase(s.begin() + i, s.end());
        else
            s.erase(s.begin() + i - 1, s.end());
    }

问题是如果输入是:“test(多个空格)test(多个空格)test。”

它将删除最后一个句点并像“test test test”一样输出

它正确地删除了空格,但不知何故它处理不当/删除了标点符号。我不希望它删除标点符号。我还是 C++ 的初学者,所以我很难弄清楚为什么。

【问题讨论】:

  • 提示:这是一个学习如何使用调试器的好用例:单步调试代码,检查每个字符发生的情况。
  • 并留意意外情况。意外是程序中的错误或您的期望。要么不好。
  • 使用调试器(或者如果太复杂,可以考虑打印中间值)。要问自己的一个问题是,当您遇到“.”时会发生什么

标签: c++ string whitespace


【解决方案1】:

因为它会不加选择地删除最后一个字符。

最后一个条件应该检查​​最后一个字符是否也是空格:

// Trim string to result
if (i <= 1 || s[i-1] != ' ')
    s.erase(s.begin() + i, s.end());
else
    s.erase(s.begin() + i - 1, s.end());

我也更正了注释,因为它不会修剪尾随空格,而是修剪操作后留下的尾随字符。该算法清除它向前移动的字符。如果您要省略最后一个条件,则输出将是: test test test. test. 用于输入 test test test.

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 2023-01-16
    • 2011-08-05
    相关资源
    最近更新 更多