Home > Net >  Assigning string chars from end to start
Assigning string chars from end to start

Time:12-16

I have been experimenting with various ways to operate on a string and wrote the following code.

std::string a = "abcde";
std::string b;
b.resize(a.length());

int times = a.length();
while (times > 0)
{
    b[times - 1] = a[b.length() - times];
    times--;
}
std::cout << b << '\n';

return 0;

The idea is to resize a string and then set single characters index by index. Now the code works, but a few days back I was getting Segmentation fault (please note, I can't remember that the code was absolutely identical to this one).

The question is, is this a legitimate piece of code (let's say, when I want to fill in a string from end to start without using inserts and reverses)?

CodePudding user response:

It doesn't look wrong, but it is very easy to get this sort of code wrong, and you have to read through it to work out what the intent is.

Hmm... generally the idea of containers is that you use the iterator notation. Of course, they are also strings of characters, and sometimes you can't avoid doing indexing operations.

But for something like this, you can quickly reverse a string by using the insert method and reverse iterator range, or the iterator range constructor for example:

std::string b {a.rbegin(), a.rend()};

Lots of ways.

CodePudding user response:

I don't see a reason for segmentation fault in the code that you posted.

But there are several more elegant ways to reverse a string.
The best way is probably to use reverse iterators as shown in the other answers.

Another alternative is to use std::reverse:

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string a = "abcde";
    std::string b = a;
    std::reverse(b.begin(), b.end());   // <---
    std::cout << a << '\n';
    std::cout << b << '\n';
}

Output:

abcde
edcba

The only drawback here is that in this scenario each character is actually copied twice (once in the initial assignment, and once during std::reverse).

CodePudding user response:

Reversing strings can be done easier in C

#include <algorithm>
#include <iostream>
#include <string>

int main() {
  std::string a = "abcde";
  std::string b;

  b.resize(a.length());
  std::copy(a.rbegin(), a.rend(), b.begin());

  std::cout << b << '\n';
}

If b is a new variable and not an existing one to modify, then it can be initialized with the required reversed string value on the declaration line

#include <algorithm>
#include <iostream>
#include <string>

int main() {
  std::string a = "abcde";

  std::string b(a.rbegin(), a.rend());

  std::cout << b << '\n';
}
  • Related