Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a string's characters alphabetically?

For Array, there is a pretty sort method to rearrange the sequence of elements. I want to achieve the same results for a String.

For example, I have a string str = "String", I want to sort it alphabetically with one simple method to "ginrSt".

Is there a native way to enable this or should I include mixins from Enumerable?

like image 715
steveyang Avatar asked Feb 27 '12 11:02

steveyang


People also ask

Can you sort a string alphabetically in Python?

Summary. Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do I sort a string alphabetically in Java 8?

We can also use Java 8 Stream for sorting a string. Java 8 provides a new method, String. chars() , which returns an IntStream (a stream of ints) representing an integer representation of characters in the String. After getting the IntStream , we sort it and collect each character in sorted order into a StringBuilder .

How do you sort an array of characters?

sort(char[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of chars into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.


2 Answers

The chars method returns an enumeration of the string's characters.

str.chars.sort.join #=> "Sginrt" 

To sort case insensitively:

str.chars.sort(&:casecmp).join #=> "ginrSt" 
like image 167
molf Avatar answered Sep 18 '22 18:09

molf


Also (just for fun)

str = "String" str.chars.sort_by(&:downcase).join #=> "ginrSt" 
like image 22
fl00r Avatar answered Sep 17 '22 18:09

fl00r