user2509901
user2509901

Reputation:

Comparing two string and sorting them in alphabetical order

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.

Upvotes: 8

Views: 67271

Answers (4)

Siva Sankaran
Siva Sankaran

Reputation: 1

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");
    }
}

Upvotes: 0

Anton Ivinskyi
Anton Ivinskyi

Reputation: 392

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]);

Upvotes: 1

Amit Sharma
Amit Sharma

Reputation: 6154

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);
}

Upvotes: 23

irla
irla

Reputation: 489

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")
}

Upvotes: 2

Related Questions