Let’s learn 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 or not first store the given string in String variable “strInput”.
Before going to next step first create static checkIfAlphabaticOrder(String str). In this method String length is found using length() method.
This length is stored in character array “chArray”. Now using for loop characters in the given string are iterated.
Now this character array is sorted using Arrays.sort() method. In the next step check if characters in sorted array are same as given string.
If they are same then print given string is in alphabetical order else print given string is not in alphabetical order on console.
import java.util.Arrays; public class CheckIfStringAlphabetical { public static void main(String[] args) { String strInput = "helloworld"; if(checkIfAlphabaticOrder(strInput)) { System.out.println("Given string is in alphabetical order."); } else { System.out.println("Given string is not in alphabetical order."); } } static boolean checkIfAlphabaticOrder(String str) { int size = str.length(); char[] chArray = new char[size]; for(int a = 0; a < size; a++) { chArray[a] = str.charAt(a); } Arrays.sort(chArray); for(int a = 0; a < size; a++) { if(chArray[a] != str.charAt(a)) { return false; } } return true; } }
Output:
Given string is not in alphabetical order.