Take the 2-minute tour ×

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++?

share|improve this question
What about std::sort? –  dreamlax Feb 2 '12 at 5:21
add comment

2 Answers

up vote 13 down vote accepted

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;
share|improve this answer
thanks, i feel stupid now, too much php... –  gprime Feb 2 '12 at 6:28
add comment
std::sort(str.begin(), str.end());

See here

share|improve this answer
This is the best way... IF the string is using a single byte encoding. Otherwise you'll break apart characters into their component bytes. –  Ben Voigt Feb 2 '12 at 5:34
@BenVoigt: excellent point! –  dreamlax Feb 2 '12 at 5:36
add comment

Your Answer


