Search code examples
javastringmethodsalphabetical

How to tell if a String is naturally sorted alphabetically or not - java


I am using Java to create a method called isOrdered to tell if a string is sorted naturally in alphabetical order. For example, if the input was "effort" or "Aaaabbyy" the method would return true, compared to "hello" that would return false since the letter 'h' appears after the letter 'e'.

I have worked out this so far,

public class orderWording {
    public static void main(String[] args) {
       System.out.println(isOrdered("effort")); //should appear true
    }
    public static boolean isOrdered (String s) {
       for (int i = 0; i < s.length(); i ++) {
            if (s.charAt(i) == /*alphabet */ ) {
                return true;
            }
            else {
                return false;
            }
       }
    }
}

However, I don't know how to match each character with the alphabet to know if the string is naturally in alphabetical order.

I thought about making a nested loop within the isOrdered method. While the first loop is traversing the string, the second loop is matching those characters with the order of the alphabet.

Something similar to this,

    public static boolean isOrdered (String s) {
       String a = 'abcdefghijklmnopqrstuvwxyz'
       for (int i = 0; i < s.length(); i ++) {
           for (int j = 0; j < a.length(); j ++){
               if (s.charAt(i) == a.charAt(j) ) {
                   return true;
               }
               else {
                   return false;
               }
           }
       }
    }

Although, I am not sure if this is a correct way to solve this problem.

Thank you for your help.


Solution

  • I think this should solve your issue. I added another method to check if it sorted in descending fashion as well.

    public class OrderWording {
        public static void main(String[] args) {
           System.out.println(isAscendingOrdered("effort")); //true
           System.out.println(isAscendingOrdered("java")); //false
           System.out.println(isDescendingOrdered("Yea")); //true
        }
    
        public static boolean isAscendingOrdered (String s) {
           s=s.toUpperCase();
           for (int i = 0; i < s.length()-1; i ++) {
              if (s.charAt(i)>s.charAt(i+1))
                  return false;                
           }
           return true;
        }
    
        public static boolean isDescendingOrdered (String s) {
           s=s.toUpperCase();
           for (int i = 0; i < s.length()-1; i ++) {
              if (s.charAt(i)<s.charAt(i+1))
                  return false;       
           }
           return true;
        }
    }
    

    Hope this helps. Cheers!