q0987 q0987 - 1 month ago 4x
C++ Question

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?


Like this:

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

std::swap is located in <algorithm>.