Home > Net >  Remove out excess spaces from string in C
Remove out excess spaces from string in C

Time:06-19

I have written program for removing excess spaces from string.

#include <iostream>
#include <string>
void RemoveExcessSpaces(std::string &s) {
  for (int i = 0; i < s.length(); i  ) {
    while (s[i] == ' ')s.erase(s.begin()   i);
    while (s[i] != ' ' && i < s.length())i  ;
  }
  if (s[s.length() - 1] == ' ')s.pop_back();
}
int main() {
  std::string s("  this is   string  ");
  RemoveExcessSpaces(s);
  std::cout << "\"" << s << "\"";
  return 0;
}

One thing is not clear to me. This while (s[i] == ' ')s.erase(s.begin() i); should remove every space in string, so the output would be thisisstring, but I got correct output which is this is string.

Could you explain me why program didn't remove one space between this and is and why I got the correct output?

Note: I cannot use auxiliary strings.

CodePudding user response:

That is because when your last while loop finds the space between your characters (this is) control pass to increment part of your for loop which will increase the value of int i then it will point to next character of given string that is i(this is string) that's why there is space between (this is).

CodePudding user response:

Your second while loop will break when s[i]==' '. But then your for loop will increment i and s[i] for that i will be skipped. This will happen for every first space character after each word.

  • Related