Sorting Characters Of A C++ String

gprime picture gprime · Feb 2, 2012 · Viewed 171.8k times · Source

If i have a string is there a built in function to sort the characters or would I have to write my own?

for example:

string word = "dabc";

I would want to change it so that:

string sortedWord = "abcd";

Maybe using char is a better option? How would I do this in C++?

Answer

R. Martinho Fernandes picture R. Martinho Fernandes · Feb 2, 2012

There is a sorting algorithm in the standard library, in the header <algorithm>. It sorts inplace, so if you do the following, your original word will become sorted.

std::sort(word.begin(), word.end());

If you don't want to lose the original, make a copy first.

std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());