4 different ways to sort string characters alphabetically in Java

Introduction:
Sometimes we need to sort all characters in a string in alphabetical order. Since String is immutable in Java, it will create a different string variable. For example, the string "albert" will become "abelrt" after sorting. In this Java example, we will learn how to sort the characters of a string alphabetically in different ways.
Let's take a look:
Use loops:
The basic method of any sorting is to use loops. We will use two for loops, and both will run inside the other. The outer loop will select one by one from the left side of the string, and the inner loop will compare it with all other elements on the left side of the string. If any element with a smaller inner loop is found, we exchange it with the element pointed to by the outer loop. Let me show you the algorithm in code:
import java.util.Arrays;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        //1
        Scanner scanner = new Scanner(System.in);

        //2
        System.out.println("Enter a string : ");
        String userInput = scanner.nextLine();

        //3
        char[] charArray = userInput.toCharArray();


        //4
        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);
                }
            }
        }

        //6
        System.out.println("Sorted string " + String.valueOf(charArray));
    }

    // 5
    private static void swapChars (int i, int j, char [] charArray) {         char temp = charArray [i];         charArray [i] = charArray [j];         charArray [j] = temp;     }



}
Explanation:
1. Create a Scanner object to read user input values.
2. Ask the user to enter a character string. Read it and store it in the userInput variable.
3. We plan to compare each character of this string and swap and arrange them in ascending order. Since the string is immutable, we need to convert the string value to an array first. For this, we use toCharArray() to return a character array.
4. Now, use two nested for loops to sort the contents of the array. Here, before comparing two characters, we convert them to lowercase letters, because uppercase and lowercase letters have different ASCII values.
5. The swapChars function is used to swap two characters in the array. It takes the position of the character in the array as input.
6. Finally, output the sorted string to the user.
Sample output:
Enter a string:
Alphabet
Sorted string Aabehlpt

Enter a string:
elephant
Sorted string aeehlnpt
does not use circular sorting:
In addition to using two for loops, we can also directly sort the character array as follows:
import java.util.Arrays;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        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 not be able to sort strings that contain both uppercase and lowercase letters . If the string is only uppercase or lowercase, it will work.
Example:
Elephant
Sorted string Eaehlnpt

Enter a string :
elephant
Sorted string aeehlnpt

Enter a string:
ELEPHANT
Sorted string AEEHLNPT
uses a comparator:
we can improve the above program to compare all uppercase and lowercase characters as follows:
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner ;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a string : ");
        String userInput = scanner.nextLine();

        //1
        Character[] charArray = new Character[userInput.length()];

        for (int i = 0; i < userInput.length(); i++) {
            charArray[i] = userInput.charAt(i);
        }

        //2
        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. First, we create a Character array from a string.
2. Then, we passed a lambda to compare the characters in the second parameter. lamda actually looks like this:
Arrays.sort(charArray, new Comparator() {

           @Override
           public int compare(Character o1, Character o2) {                return Character.compare(Character.toLowerCase(o1),                        Character.toLowerCase(o2));            }        }); Finally, we use StringBuilder to convert the array to a string. It will arrange the characters as expected. Example: Enter a string: Elephant Sorted string aEehlnpt uses Java Stream: The Java 8 Stream API provides a beautiful way to solve this problem. import java.util.Comparator; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.Stream;














class Main {
    public static void main(String[] args) {
        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);
    }
}
Here, we use the same comparator as above in the sorted() method. It will give the following output:
Enter a string:
Elephant
Sorted string aEehlnpt
 
Conclusion:
In Java, we have seen four different ways to sort characters in a string. In fact, the second method and the third method are the same. You can use the third one instead of the second to support all uppercase and lowercase letters. Which method you use depends on your requirements.

Guess you like

Origin blog.csdn.net/allway2/article/details/114366087