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?
Like this:
std::swap(tmpStr[0], tmpStr[1]);
std::swap
is located in <algorithm>
.
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.
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.
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.
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
How about:
std::string s("ab");
s[0] = 'b';
s[1] = 'c';
Or
std::string s("ab");
s = std::string("bc");
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.