q0987
q0987

Reputation: 35982

C++ string - how to swap a string with two characters?

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?

Upvotes: 0

Views: 6270

Answers (6)

Oleg Razgulyaev
Oleg Razgulyaev

Reputation: 5935

Look at this :)

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

Explanation:

The XOR operator has the 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

The result is b,a.

Upvotes: 2

Steve Townsend
Steve Townsend

Reputation: 54138

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.

Upvotes: 6

Mario The Spoon
Mario The Spoon

Reputation: 4859

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

Upvotes: 0

sellibitze
sellibitze

Reputation: 28097

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.

Upvotes: 2

GManNickG
GManNickG

Reputation: 503825

Like this:

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

std::swap is located in <algorithm>.

Upvotes: 17

rubenvb
rubenvb

Reputation: 76519

How about:

std::string s("ab");

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

Or

std::string s("ab");

s = std::string("bc");

Upvotes: -2

Related Questions