Sorting Characters Of A C++ String

C++StringSorting

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

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());

Solution 2 - C++

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

See here

Solution 3 - C++

You have to include http://www.cplusplus.com/reference/algorithm/sort/">`sort`</a> function which is in http://www.cplusplus.com/reference/algorithm/">`algorithm`</a> header file which is a http://www.cplusplus.com/reference/stl/">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

Solution 4 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongprimeView Question on Stackoverflow
Solution 1 - C++R. Martinho FernandesView Answer on Stackoverflow
Solution 2 - C++dreamlaxView Answer on Stackoverflow
Solution 3 - C++abe312View Answer on Stackoverflow
Solution 4 - C++rashedcsView Answer on Stackoverflow