Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a string alphabetically using a function

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?

like image 629
Marco V Avatar asked Jun 18 '15 10:06

Marco V


People also ask

How do you sort a string in alphabetical order?

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.

How do you sort a string by function?

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

How do you sort a string alphabetically in Python with sort function?

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.

How do I sort a string in alphabetical order in Javascript?

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.


2 Answers

You can use array sort function:

var sortAlphabets = function(text) {     return text.split('').sort().join(''); }; 

STEPS

  1. Convert string to array
  2. Sort array
  3. Convert back array to string

Demo

like image 195
Tushar Avatar answered Sep 30 '22 16:09

Tushar


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(""); } 
like image 25
marvinhagemeister Avatar answered Sep 30 '22 16:09

marvinhagemeister