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

C++ 删除c+中多余的空格+;问题,c++,string,whitespace,punctuation,remove,C++,String,Whitespace,Punctuation,Remove,我从网上得到了这个代码片段 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; //

我从网上得到了这个代码片段


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


void ShortenSpace(字符串和s)
{
//n是原始字符串的长度
int n=s.长度();
//指针i用于跟踪下一个位置,指针j用于遍历
int i=0,j=-1;
//如果找到空间,则设置为true的标志
bool spaceFound=false;
//处理前导空格
而(++j=0&&
s[i-1]=='')
s[i-1]=s[j++];
其他的
//将当前字符复制到索引i
//同时增加i和j
s[i++]=s[j++];
//如果出现任何错误,请将空格标志设置为false
//找到非空格字符
spaceFound=false;
}
//如果当前字符是空格
否则如果(s[j++]='')
{
//如果在一个单词后第一次看到空格
如果(!spaceFound)
{
s[i++]='';
spaceFound=true;
}
}
}
//删除尾随空格

if(i,因为它不加区别地删除最后一个字符

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

//将字符串修剪为结果

如果(我暗示:这是一个很好的用例来学习如何使用调试器:对代码进行一步检查,并检查每个字符会发生什么,并密切注意意外情况。意外的是程序中的一个bug或您的期望。要么是坏的。使用调试器(或者如果太复杂,考虑打印中间值))。.要问自己的一个问题是,当你遇到一个“.”时会发生什么?这太完美了。非常感谢!