how to check if a string is in alphabetical order in java

how to check if a string is in alphabetical order in java

To check if a string is in alphabetical order in Java, you can iterate through the characters in the string and compare them using the compareTo method of the Character class.

Here's an example of how you might do this:

ref‮‬er to:lautturi.com
String str = "abcdefg";

boolean isAlphabetical = true;
for (int i = 0; i < str.length() - 1; i++) {
    if (Character.compare(str.charAt(i), str.charAt(i + 1)) > 0) {
        isAlphabetical = false;
        break;
    }
}

if (isAlphabetical) {
    System.out.println("The string is in alphabetical order.");
} else {
    System.out.println("The string is not in alphabetical order.");
}

In this example, the charAt method is used to get the character at a specific index in the string, and the compareTo method is used to compare the characters. If the characters are not in alphabetical order, the isAlphabetical variable is set to false and the loop is terminated.

After the loop, the isAlphabetical variable is checked, and the appropriate message is printed to the console.

You can use this approach to check if a string is in alphabetical order as needed.

Created Time:2017-11-01 12:05:14  Author:lautturi