tags:

views:

162

answers:

6

Hello all,

Given a C++ string str("ab"), how do I swap the content of str so that it becomes "ba". Here is my code:

    string tmpStr("ab");

    const char& tmpChar = tmpStr[0];
    tmpStr[0] = tmpStr[1];
    tmpStr[1] = tmpChar;

Is there a better way?

Thank you

+17  A: 

Like this:

std::swap(tmpStr[0], tmpStr[1]);

std::swap is located in <algorithm>.

GMan
Probably what OP wanted
John Dibling
Definitely +1 for std::swap.
DeadMG
A: 

How about:

std::string s("ab");

s[0] = 'b';
s[1] = 'c';

Or

std::string s("ab");

s = std::string("bc");
rubenvb
Clearly this is not what OP was asking for...
John Dibling
@John: no so clear. He wanted to get the result "bc".
ybungalobill
Hello rubenvb, Sorry for my typo and thank you for your answer.
q0987
@ybungalobill - OP's code is clear enough even if text is (or was) not.
Steve Townsend
@ybunaglobill: "how do I swap the content of str" seems quite clear to me.
John Dibling
+6  A: 

If you want a sledgehammer for this nut:

#include <algorithm>
using namespace std;

string value("ab");
reverse(value.begin(), value.end());

This one might be useful for the followup question involving "abc", though swap is preferred for the two-element case.

Steve Townsend
+1 for being applicable to larger strings.
GMan
+1 for being general rather than specific.
Jookia
+1 for being the best answer for complete strings
Mario The Spoon
+1 for three +1 comments.
GMan
+2  A: 

Of course, std::swap would be the right thing to do here, as GMan pointed out. But let me explain the problem with your code:

string tmpStr("ab");
const char& tmpChar = tmpStr[0];
tmpStr[0] = tmpStr[1];
tmpStr[1] = tmpChar;

tmpChar is actually a reference to tmpStr[0]. So, this is what will happen:

| a | b |  (initial content, tmpChar refers to first character)
| b | b |  (after first assignment)

Note, that since tmpChar refers to the first character, it now evaluates to 'b' and the second assignment does effectivly nothing:

| b | b |  (after second assignment)

If you remove the & and make tmpChar an actual character variable, it'll work.

sellibitze
A: 

If you need to get the characters one by one use an revers iterator as shown here

// string::rbegin and string::rend
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("now step live...");
  string::reverse_iterator rit;
  for ( rit=str.rbegin() ; rit < str.rend(); rit++ )
    cout << *rit;
  return 0;
}

hth

Mario

Mario The Spoon
+1  A: 

look at this :)

tmpStr[0] ^= tmpStr[1];
tmpStr[1] ^= tmpStr[0];
tmpStr[0] ^= tmpStr[1];

explanation:

XOR op has property: (x^y)^y = x
let's we have a,b

1 => a^b,b
2 => a^b,b^a^b=a
3 => a^b^a=b,a

result b,a
oraz
+1 if you explain why this works
Marlon
Don't actually do this. It's slower on modern CPU's, and ugly.
GMan