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.
This is what I tried
#include <iostream>
#include <string>
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 < s.length() - 1; i++) { // this does NOT work
if(s.at(i) == ' ' && 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 << "|" << s << "|" << endl;
cout << "|" << s1 << "|" << endl;
return 0;
}
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?
EDIT 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.
auto it3= s.begin();
for(int i = 0; i < s.length() - 1; i++) {
if(s.at(i) == ' ' && s.at(i + 1) == ' ') {
s.erase(s.begin()+i);
i--;
}
}
Thank you all for helping me.