q0987 q0987 - 2 months ago 12
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?

Answer

Like this:

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

std::swap is located in <algorithm>.