102

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

gprime
  • 2,283
  • 7
  • 38
  • 50

4 Answers4

182

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());
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • What if we want the string to sorted in increasing order? – The Room Jun 16 '17 at 14:09
  • 6
    @madhuspot `std::sort` sorts in alphabetically-increasing order by default. Supposing that's a minor typo and you want **de**creasing 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());` — that would give a result of "dcba" in the original question rather than "abcd". – Tommy Jul 10 '17 at 00:19
  • 4
    @madhuspot or use std::reverse – Vincent Jan 30 '18 at 18:18
17
std::sort(str.begin(), str.end());

See here

dreamlax
  • 93,976
  • 29
  • 161
  • 209
  • 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 Feb 02 '12 at 05:34
3

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

abe312
  • 2,547
  • 25
  • 16
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

rashedcs
  • 3,588
  • 2
  • 39
  • 40