简体   繁体   中英

Is this reverse string code correct?

This code works for me when I run it on my IDE, but it doesn't work on the website that has the exercise. I get a segmentation fault. So is this code correct? Did I make a mistake?

#include <iostream>
#include <string>
using namespace std;

string FirstReverse(string str) { 
  for (int i = 0, back = str.size()-1; i != back; ++i, --back)
  {
    char c = str[back];
    str[back] = str[i];
    str[i] = c;
  }
  return str; 
}

int main() {
  cout << FirstReverse("hello");
  return 0;
}

Also, what's the best way to do this?

Your index only needs to reach half of the length, and that way we ensure that the swap between a pair only happens once:

for (int i = 0; i < str.size() / 2 ; i ++)
{
    char c = str[str.size() - 1 - i];
    str[str.size() - 1 - i] = str[i];
    str[i] = c;

}

If you change the loop condition to "i <= back" then it won't cause segmentation fault. It is because when size-1 is even , i & back will never become equal. Thus loop will keep on going without breaking & attempt to access string member outside the string.

只需将您的条件从!=更改为<=解决。

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