Java sorting strings alphabetically

4 ways in Java to sort a String alphabetically

This blog will show you how to sort a String alphabetically in Java . For example, the String ‘albert’ will become ‘abelrt’ after sorting. Since String is immutable, it will create a new String with the sorted characters. We will learn four different ways with examples in this post.

Method 1: By using two loops:

This is the simplest way to sort a String . We will use two for loops and one loop will run inside another loop. The outer loop will iterate over the characters one by one and for each character, the inner loop will compare it with all other characters to the right of that character. If any alphabetically small character is found by the inner loop, it will swap it with the character pointed by the outer loop.

The following program shows how to write this in Java :

import java.util.Scanner; class FirstExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); char[] charArray = userInput.toCharArray(); for (int i = 0; i  charArray.length; i++)  for (int j = i + 1; j  charArray.length; j++)  if (Character.toLowerCase(charArray[j])  Character.toLowerCase(charArray[i]))  swapChars(i, j, charArray); > > > System.out.println("Sorted string " + String.valueOf(charArray)); > > private static void swapChars(int i, int j, char[] charArray)  char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; > >

The commented numbers in the above program denote the step numbers below:

Create one Scanner object to read the user input String .

Ask the user to enter a String . Read it and assign it to the userInput variable.

We need to compare each character of this String , swap, and arrange them in ascending order. Since a String is immutable, we need to convert the String to an Array . It is using the toCharArray() method to convert it to an array of characters. It assigns the value to the charArray variable.

It uses two nested for loops to sort the characters of the array. It converts the characters to lowercase before comparing.

The swapChars method is used to swap two characters in an array. It takes the position of the characters in an array and the array as its parameters. If the character at index j is smaller than the character at index i , it swaps the characters of these positions.

Finally, print out the sorted string to the user. It uses the String.valueOf method to convert the character array to String .

If you run the above program, it will print outputs as below:

Enter a string : Alphabet Sorted string Aabehlpt Enter a string : elephant Sorted string aeehlnpt

Method 2: Sort a String by converting it to an Array :

The previous method converts the String to an array of characters and used two for loops to sort the characters. We can also use the Arrays.sort method to sort the content of the character array. The sorted array can be converted back to a String .

The following program shows how it works:

import java.util.Arrays; import java.util.Scanner; class SecondExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); char[] charArray = userInput.toCharArray(); Arrays.sort(charArray); System.out.println("Sorted string: " + String.valueOf(charArray)); > > >

The only problem with this method is that it will fail to sort a string with both uppercase and lowercase letters. If the String has only uppercase or lowercase letters, it will work.

Enter a string: Elephant Sorted string: Eaehlnpt Enter a string: elephant Sorted string: aeehlnpt Enter a string: ELEPHANT Sorted string: AEEHLNPT

As you can see here, the first example failed as the ASCII value of E is 69 and the ASCII value of a is 97. So, it placed E before a .

Java sort string example

Method 3: How to sort a String by using a comparator:

We can use a Comparator with the Arrays.sort() method. We need to convert the string to a Character array. The following program shows how to sort a given String with a comparator:

import java.util.Arrays; import java.util.Comparator; import java.util.Scanner; class ThirdExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); Character[] charArray = new Character[userInput.length()]; for (int i = 0; i  userInput.length(); i++)  charArray[i] = userInput.charAt(i); > Arrays.sort(charArray, Comparator.comparingInt(Character::toLowerCase)); StringBuilder sb = new StringBuilder(charArray.length); for (Character c : charArray) sb.append(c.charValue()); System.out.println("Sorted string: " + sb.toString()); > > >
  1. It creates one Character array from the string. It is assigned to the charArray variable.
  2. It passes one lambda function to the sort method.
Arrays.sort(charArray, new Comparator()  @Override public int compare(Character o1, Character o2)  return Character.compare(Character.toLowerCase(o1), Character.toLowerCase(o2)); > >);

Finally, it converts the character array to a StringBuilder object and it is converted back to String by using the toString() method.

The above program will print output as below:

Enter a string: Elephant Sorted string: aEehlnpt

Method 4: Sort a String by using Stream :

Another way is to use the Stream API to sort the characters. We can convert the String to a Stream , sort the characters and convert it back to a String . The following program shows how it works:

import java.util.Comparator; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.Stream; class FourthExample  public static void main(String[] args)  try (Scanner scanner = new Scanner(System.in))  System.out.println("Enter a string:"); String userInput = scanner.nextLine(); String finalString = Stream.of(userInput.split("")) .sorted(Comparator.comparingInt(o -> Character.toLowerCase(o.charAt(0)))) .collect(Collectors.joining()); System.out.println("Sorted string: " + finalString); > > >

We are using the same comparator function in the sorted() method. If you run the program, it will print output as below:

Enter a string: Elephant Sorted string: aEehlnpt

java sort string character alphabetically

We have learned four different ways to sort the characters in a string in Java. You can raise a PR on GitHub if you want to add anything else.

Источник

Sort a String Alphabetically in Java

This Java tutorial discusses the different approaches to sort a string alphabetically. When sorting alphabetically, we essentially sort the characters of the string in alphabetical order.

1. Sort a String using Java 8 Streams

The Stream.sorted() method sorts the stream elements in the natural order. In case of strings, the natural order is the alphabetical order. So we need to perform the following pseudo steps:

  • Create a stream of characters from the String
  • Sort the stream
  • Join the Stream to get a new sorted string

The following Java program demonstrates sorting the characters of a string using Stream.sorted() API.

String string = "adcbgekhs"; String sortedString = Stream.of( string.split("") ) .sorted() .collect(Collectors.joining()); System.out.println(sortedString); // abcdeghks

2. Sort a String using Arrays.sort()

The Arrays.sort() also does the same thing as Stream.sort() does. So the steps to sort a string remains the same in this solution also. This time, we create a new array of characters, sort the array and then join the array to produce the sorted string.

String string = "adcbgekhs"; //Convert string to char array char[] chars = string.toCharArray(); //Sort char array Arrays.sort(chars); //Convert char array to string String sortedString = String.valueOf(chars); System.out.println(sortedChars); // abcdeghks

3. Without using sort() Method

If we do not want to use the inbuilt Java APIs, we can use the Java arrays to iterate over the characters of the String and sort them in a loop.

  • Convert string to an array of characters using toCharArray() method
  • Loop through the array elements and check for swapping elements of an array by comparing the code value
  • Print the array after the loop finishes
String string = "adcbgekhs"; String sortedString = sortWithArray(string); System.out.println(sortedString); //The custom sorting function using arrays static String sortWithArray(String str) < char arr[] = str.toCharArray(); char temp; int i = 0; while (i < arr.length) < int j = i + 1; while (j < arr.length) < if (arr[j] < arr[i]) < temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; >j += 1; > i += 1; > return String.copyValueOf(arr); >

This Java tutorial discusses different ways to sort a string alphabetically with examples. We learned to use the Stream.sort(), Arrays.sort() and custom sort() method using simple arrays and swapping.

Drop me your questions in the comments section.

Источник

Читайте также:  Javascript кнопка перезагрузка страницы
Оцените статью