从 C++ 问题中删除多余的空格

Remove extra whitespace from c++ issue

我从网上获得了这段代码。


    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 (multiple spaces) test (multiple spaces) test.”

它将删除最后一个句点并输出类似“test test test”的输出

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

因为它乱删了最后一个字符

最后一个条件还应检查最后一个字符是否为白色 space:

// 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());

我也更正了评论,因为它没有 trim 尾随的白色 spaces,而是处理后留下的尾随字符。该算法清除它向前移动的字符。如果省略最后一个条件,输出将是: test test test. test. 输入 test test test.