How to Sort a String's Characters Alphabetically

Sorting characters alphabetically in a String

You may do the following thing -

1. Convert your String to char[] array.

2. Using Arrays.sort() sort your char array

Code snippet:

String input = "hello";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);

Or if you want to sort the array using for loop (for learning purpose) you may use (But I think the first one is best option ) the following code snippet-

input="hello";
char[] charArray = input.toCharArray();
length = charArray.length();

for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if (charArray[j] < charArray[i]) {
char temp = charArray[i];
charArray[i]=arr[j];
charArray[j]=temp;
}
}
}

How to sort the letters in a string alphabetically in Python

You can do:

>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'

How to sort a string's characters alphabetically?

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"

Sort a string alphabetically using a function

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

Sorting a String by its 6 first characters

you can sort the list by the first 6 characters and then use Collectors.joining to separate each string with a "\n" delimiter.

String result = myList.stream().sorted(Comparator.comparing(e -> e.substring(0,6)))
.collect(Collectors.joining("\n"));

Is there a simple way that I can sort characters in a string in alphabetical order

You can use LINQ:

String.Concat(str.OrderBy(c => c))

If you want to remove duplicates, add .Distinct().

Python: How to sort the letters in a string alphabetically keeping distinction between uppercases and lowercases

sorted() sorts based off of the ordinal of each character. Capital letters have ordinals that are lower than all lowercase letters. If you want different behavior, you'll need to define your own key:

c = sorted(s, key=lambda c: (c.lower(), c.islower()))

That way, c would be sorted by ('c', 1) and C is sorted by ('c', 0). Both come before ('d', ...) or ('e', ...) etc., but the capital C is earlier (lower) than the lowercase c.

By the way, you shouldn't say d = "".join(sorted(c)) because c has already been sorted. Just do d = "".join(c)



Related Topics



Leave a reply



Submit