简体   繁体   中英

Remove out excess spaces from string in C++

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.

那是因为当你的最后一个while循环找到你的字符之间的空间(这是)控制传递来增加你的for循环的一部分,这将增加int i的值然后它将指向给定字符串的下一个字符,即i(这个是字符串),这就是为什么(这是)之间有空格。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM