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
?
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.
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 .
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.
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"
Also (just for fun)
str = "String" str.chars.sort_by(&:downcase).join #=> "ginrSt"
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