Remove extra white spaces in C++

前端 未结 12 1790
日久生厌
日久生厌 2021-02-05 12:01

I tried to write a script that removes extra white spaces but I didn\'t manage to finish it.

Basically I want to transform abc sssd g g sdg gg gf into

12条回答
  •  伪装坚强ぢ
    2021-02-05 12:19

    I don't know if this helps but this is how I did it on my homework. The only case where it might break a bit is when there is spaces at the beginning of the string EX " wor ds " In that case, it will change it to " wor ds"

    void ShortenSpace(string &usrStr){
       char cha1;
       char cha2;
       for (int i = 0; i < usrStr.size() - 1; ++i) {
          cha1 = usrStr.at(i);
          cha2 = usrStr.at(i + 1);
          
          if ((cha1 == ' ') && (cha2 == ' ')) {
             usrStr.erase(usrStr.begin() + 1 + i);
             --i;//edit: was ++i instead of --i, made code not work properly
          }
       }
    }
    

提交回复
热议问题