8

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.

4 Answers4

23

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);
}
Amit Sharma
  • 5,844
  • 5
  • 25
  • 34
  • 2
    If you are not in plain ascii mode this strategy wont wokr right. See http://stackoverflow.com/a/12927962/2087666 – Remi Morin Dec 19 '14 at 16:35
  • Caution: ASCII values of capital letters are less than that of small letters. If cases are like 1> a="Ax" and b="aa" or 2> a="aa" and b="AA"...The results will be a contradiction to expected alphabetical sorting. Better convert both strings in a common "CASE" and then compare. – Deepeshkumar Sep 19 '15 at 11:55
2
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("Strings are equal")
}
irla
  • 479
  • 3
  • 13
1

If you just look for an easy and elegant code and you do not want to preoptimize, in java 8 you can do like this:

String[] sorted = Stream.of(a, b).sorted().toArray(String[]::new);
System.out.println(sorted[0] + " is before " + sorted[1]);
Anton Ivinskyi
  • 402
  • 5
  • 17
0

Here is the code for the problem.

 public static void main(String[] args) {
    String a="Angram";
    String b="Angram";

    if(a.length()==b.length()) {
        char c[]=a.toCharArray();
        char d[]=b.toCharArray();
        Arrays.sort(c);
        Arrays.sort(d);
        a=new String(c);
        b=new String(d);
        if(a.equals(b)) 
            System.out.print("Yes");
        else
            System.out.print("No");
    }
    else {
        System.out.print("No");
    }
}
Avishek Bhattacharya
  • 6,534
  • 3
  • 34
  • 53