Sorting Characters Of A C++ String
C++StringSortingC++ 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