106

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

2
  • 7
    What about std::sort?
    – dreamlax
    Commented Feb 2, 2012 at 5:21
  • Note that any sort of naive char value based sorting breaks with UTF-8 -- depending on your strings you might want to take the locale into consideration. Commented Nov 17, 2017 at 10:44

4 Answers 4

188

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());
3
  • What if we want the string to sorted in increasing order?
    – The Room
    Commented Jun 16, 2017 at 14:09
  • 7
    @madhuspot std::sort sorts in alphabetically-increasing order by default. Supposing that's a minor typo and you want decreasing order, use the version of std::sort that takes a Compare as its third argument and supply std::greater instead of the default std::less. std::string uses the char type by default so e.g. std::sort(sortedWord.begin(), sortedWord.end(), std::greater<char>()); — that would give a result of "dcba" in the original question rather than "abcd".
    – Tommy
    Commented Jul 10, 2017 at 0:19
  • 5
    @madhuspot or use std::reverse
    – Vincent
    Commented Jan 30, 2018 at 18:18
17
std::sort(str.begin(), str.end());

See here

1
  • 11
    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
    Commented Feb 2, 2012 at 5:34
4

You have to include sort function which is in algorithm header file which is a standard template library in c++.

Usage: std::sort(str.begin(), str.end());

#include <iostream>
#include <algorithm>  // this header is required for std::sort to work
int main()
{
    std::string s = "dacb";
    std::sort(s.begin(), s.end());
    std::cout << s << std::endl;

    return 0;
}

OUTPUT:

abcd

2

You can use sort() function. sort() exists in algorithm header file

        #include<bits/stdc++.h>
        using namespace std;


        int main()
        {
            ios::sync_with_stdio(false);
            string str = "sharlock";

            sort(str.begin(), str.end());
            cout<<str<<endl;

            return 0;
        }

Output:

achklors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.