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++?
The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.
Firstly, set a string array. string[] values = { "tim", "amit", "tom", "jack", "saurav"}; Use the Sort() method to sort.
Sort characters of a string in C++ The standard and efficient solution to inplace sort characters of a string is using the std::sort algorithm from header <algorithm> . It is usually implemented using the Introsort algorithm, which is a hybrid of quicksort, heapsort, and insertion sort.
char charArray[] = {'A','Z', 'K', 'L' }; size_t arraySize = sizeof(charArray)/sizeof(*charArray); std::sort(charArray, charArray+arraySize); //print charArray : it will print all chars in ascending order. By the way, you should avoid using c-style arrays, and should prefer using std::array or std::vector .
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());
std::sort(str.begin(), str.end());
See here
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With