Comparing two string and sorting them in alphabetical order

java, sorting, string

Solution

Hint: All basic data type classes in java implement Comparable interface.

String a="LetterA";
String b="ALetterB";
int compare = a.compareTo(b);
if (compare < 0){
    System.out.println(a+" is before "+b);
}
else if (compare > 0) {
    System.out.println(b+" is before "+a);
}
else {
    System.out.println(b+" is same as "+a);
}

Problem

I want to compare two strings and sort them in alphabetical order. I am currently creating two arrays with the strings and sorting one them comparing the two arrays. ``` String a="LetterA"; String b="ALetterB"; String[] array1={a.toLowerCase(),b.toLowerCase()}; String[] array2={a.toLowerCase(),b.toLowerCase()}; Arrays.sort(array2); if (Arrays.equals(array1, array2)){ System.out.println(a+" is before "+b); } else{ System.out.println(b+" is before "+a); } ``` This works but it is time and memory consuming. I would appreciate if anyone can suggest a better way to do this.

Original source

Related problems