title: Removing extra whitespaces from a string
body: <p>I came across an interesting exercise. Basically I have to remove all excessive spaces from a string, and by excessive I mean all the spaces at the beginning of the string, at the end of the string, and there should not be more than two consecutive whitespaces. </p>
  
  <p>This is what I tried</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;string&gt;
  using namespace std;
  
  string RemoveSpaces(string s) {
      auto it = s.begin();
      while(*it == ' ') { // removes spaces at the beginning
          if(*it == ' ') s.erase(it);
      }
  
      auto it2 = s.end(); // removes spaces at the end of a string
      it2--;
  
      while(*it2 == ' ') it2--;
      it2++;
      while(*it2 == ' ') {
          if(*it2 == ' ') s.erase(it2);
      }
  
      for(int i = 0; i &lt; s.length() - 1; i++) { // this does NOT work
          if(s.at(i) == ' ' &amp;&amp; s.at(i + 1) == ' ') {
              auto it3 = s.at(i);
              s.erase(it3);
          }
      }
  
      return s;
  }
  
  int main() {
      string s;
      getline(cin, s);
  
      string s1 = RemoveSpaces(s);
  
      cout &lt;&lt; "|" &lt;&lt; s &lt;&lt; "|" &lt;&lt; endl;
      cout &lt;&lt; "|" &lt;&lt; s1 &lt;&lt; "|" &lt;&lt; endl;
  
      return 0;
  }
  
  
  </code></pre>
  
  <p>However this does not do what I expected it to do. My code successfully removes the spaces at the beginning and the end of a string, but I cannot go further than that. Can anyone help?</p>
  
  <p><strong><em>EDIT</em></strong> I fixed the problem. Here is the part of code that now deletes extra whitespaces between words, so that it leaves just one space between two words. </p>
  
  <pre><code>    auto it3= s.begin();
  
      for(int i = 0; i &lt; s.length() - 1; i++) {
          if(s.at(i) == ' ' &amp;&amp; s.at(i + 1) == ' ') {
              s.erase(s.begin()+i);
              i--;
          }
  
      }
  </code></pre>
  
  <p>Thank you all for helping me.</p>