107

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
  • 8
    What about std::sort? 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

190

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());
Sign up to request clarification or add additional context in comments.

3 Comments

What if we want the string to sorted in increasing order?
@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".
@madhuspot or use std::reverse
18
std::sort(str.begin(), str.end());

See here

1 Comment

This is the best way... IF the string is using a single byte encoding. Otherwise you'll break apart characters into their component bytes.
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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.