C++字符串 - 如何用两个字符交换字符串?

q09*_*987 0 c++

给定一个C++字符串str("ab"),如何交换str的内容使其变为"ba"?

这是我的代码:

string tmpStr("ab");

const char& tmpChar = tmpStr[0];
tmpStr[0] = tmpStr[1];
tmpStr[1] = tmpChar;
Run Code Online (Sandbox Code Playgroud)

有没有更好的办法?

GMa*_*ckG 17

像这样:

std::swap(tmpStr[0], tmpStr[1]);
Run Code Online (Sandbox Code Playgroud)

std::swap位于<algorithm>.


Ste*_*end 6

如果你想要一把大锤用于这个坚果:

#include <algorithm>
using namespace std;

string value("ab");
reverse(value.begin(), value.end());
Run Code Online (Sandbox Code Playgroud)

这个可能对涉及"abc"的后续问题很有用,但swap对于双元素情况是优选的.