Imagine you were given a string and you had to sort that string alphabetically using a function. Example:
sortAlphabets( 'drpoklj' ); //=> returns 'djklopr'
What would be the best way to do this?
Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.
For example, to sort the string in descending order, use the std::greater<>() function object, which delegates the call to operator> . Since C++14, we can skip the template arguments to std::greater function object. i.e., std::greater<>() will work. That's all about sorting the characters of a string in C++.
Use sorted() and str. join() to sort a string alphabetically in Python. Another alternative is to use reduce() method. It applies a join function on the sorted list using the '+' operator.
The sort() method sorts the strings in alphabetical and ascending order. The for...of loop is used to iterate over the array elements and display them.
You can use array sort
function:
var sortAlphabets = function(text) { return text.split('').sort().join(''); };
STEPS
string
to array
array
array
to string
Demo
Newer browsers support String.prototype.localeCompare() which makes sorting utf8
encoded strings really simple. Note that different languages may have a different order of characters. More information on MDN about localCompare.
function sortAlphabet(str) { return [...str].sort((a, b) => a.localeCompare(b)).join(""); } console.log(sortAlphabet("drpoklj")); // Logs: "djklopr"
If you only have to support ascii strings then the default sorting implementation will do.
function sortAlphabet(str) { return [...str].sort().join(""); }
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