Home > Back-end >  Reverse string with one space
Reverse string with one space

Time:05-01

I need to reverse string but to keep only one space between words.

EXAMPLE:

"  na vrh   brda vrbaa   mrdaa!!!   "
"!!!aadrm aabrv adrb hrv an"

Code:

#include <iostream>
#include <string>

std::string ReverseOneSpace(std::string s) {
  std::string str = s;
  int j = 0;
  for (int i = s.length() - 1; i >= 0; i--) {
    // skip spaces
    while (s[i] == ' ' && i >= 0)
      i--;
    while (s[i] != ' ' && i >= 0) {
      str[j] = s[i];
      j  ;
      i--;
    }
    // add only one space
    if (s[i] == ' ') str[j] = ' ';
    j  ;
    if (i == 0) break;
  }
  return str;
}
int main() {
  std::string s = "  na vrh   brda vrbaa   mrdaa!!!   ";
  std::string str = ReverseOneSpace(s);
  std::cout << "\"" << str << "\"" << std::endl;
  std::cout << "\"" << "!!!aadrm aabrv adrb hrv an" << "\"";
  return 0;
}

OUTPUT:

"!!!aadrm aabrv adrb hrv an aa!!!   " // my output
"!!!aadrm aabrv adrb hrv an" // correct

Why do I have some extra characters after the string was reversed?

CodePudding user response:

In both of your while loop, you are running out of bounds. Variable i will be "-1" in the end.

Please change your condition in your while loops from >= to >.

Additional cause may be some design issue. You should never change the loop variable (herei) within the loop body with other statements.

#include <iostream>
#include <string>

std::string ReverseOneSpace(std::string s) {
    std::string str = s;
    int j = 0;
    for (int i = s.length() - 1; i >= 0; i--) {
        // skip spaces
        while (s[i] == ' ' && i > 0)   // ************
            i--;
        while (s[i] != ' ' && i > 0) { // ************ 
            str[j] = s[i];
            j  ;
            i--;
        }
        // add only one space
        if (s[i] == ' ') str[j] = ' ';
        j  ;
        if (i == 0) break;
    }
    return str;
}
int main() {
    std::string s = "  na vrh   brda vrbaa   mrdaa!!!   ";
    std::string str = ReverseOneSpace(s);
    std::cout << "\"" << str << "\"" << std::endl;
    std::cout << "\"" << "!!!aadrm aabrv adrb hrv an" << "\"";
    return 0;
}
  • Related