q0987 q0987 - 1 year ago 58
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 Source

Like this:

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

std::swap is located in <algorithm>.