Makky
Makky

Reputation: 17461

Comparing strings by their alphabetical order

String s1 = "Project";
String s2 = "Sunject";

I want to compare the two above string by their alphabetic order (which in this case "Project" then "Sunject" as "P" comes before "S"). Does anyone know how to do that in Java?

Upvotes: 158

Views: 518982

Answers (9)

Suraj Nayak
Suraj Nayak

Reputation: 21

String s1 = "Project";
String s2 = "Sunject";

//print smaller one using compareTo() function
if(s1.compareTo(s2)<0) System.out.println(s1);
//if s1 is smaller then function returns negative which is less than 0 so s1 
//is smaller
else System.out.println(s2); // else s2 is smaller

//print larger one using compareTo() function
if(s1.compareTo(s2)>0) System.out.println(s1);
//is s1 is larger function will give positive so print s1 else s2 
else System.out.println(s2);

Upvotes: 2

Donald Duck
Donald Duck

Reputation: 8892

As others have mentioned, you can use String.compareTo, but that will sort all upper-case letters before all lower-case letters, so "Z" will come before "a".

If you just want to sort them in alphabetical order regardless of case (so that "a" comes before "Z"), you can use String.compareToIgnoreCase:

s1.compareToIgnoreCase(s2);

This returns a negative integer if s1 comes before s2, a positive integer if s2 comes before s1, and zero if they're equal. Since this method ignores case completely, two strings that differ only by case are considered equal, for example "ABC".compareToIgnoreCase("abc") will return zero.

Upvotes: 3

arenaq
arenaq

Reputation: 2380

As others suggested, you can use String.compareTo(String).

But if you are sorting a list of Strings and you need a Comparator, you don't have to implement it, you can use Comparator.naturalOrder() or Comparator.reverseOrder().

Upvotes: 1

malik arman
malik arman

Reputation: 29

import java.io.*;
import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
       Scanner sc = new Scanner(System.in);
           int n =Integer.parseInt(sc.nextLine());
           String arr[] = new String[n];
        for (int i = 0; i < arr.length; i++) {
                arr[i] = sc.nextLine();
                }


         for(int i = 0; i <arr.length; ++i) {
            for (int j = i + 1; j <arr.length; ++j) {
                if (arr[i].compareTo(arr[j]) > 0) {
                    String temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        for(int i = 0; i <arr.length; i++) {
            System.out.println(arr[i]);
        }
   }
}

Upvotes: 2

mdaguerre
mdaguerre

Reputation: 1267

String a = "..."; 
String b = "...";  

int compare = a.compareTo(b);  

if (compare < 0) {  
    //a is smaller
}
else if (compare > 0) {
    //a is larger 
}
else {  
    //a is equal to b
} 

Upvotes: 57

Buhb
Buhb

Reputation: 7149

String.compareTo might or might not be what you need.

Take a look at this link if you need localized ordering of strings.

Upvotes: 170

Ondra Žižka
Ondra Žižka

Reputation: 46796

For alphabetical order following nationalization, use Collator.

//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
    System.out.println("Strings are equivalent");
}

For a list of supported locales, see JDK 8 and JRE 8 Supported Locales.

Upvotes: 7

dogbane
dogbane

Reputation: 274612

Take a look at the String.compareTo method.

s1.compareTo(s2)

From the javadocs:

The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true.

Upvotes: 131

Vasiliy Sharapov
Vasiliy Sharapov

Reputation: 1057

You can call either string's compareTo method (java.lang.String.compareTo). This feature is well documented on the java documentation site.

Here is a short program that demonstrates it:

class StringCompareExample {
    public static void main(String args[]){
        String s1 = "Project"; String s2 = "Sunject";
        verboseCompare(s1, s2);
        verboseCompare(s2, s1);
        verboseCompare(s1, s1);
    }

    public static void verboseCompare(String s1, String s2){
        System.out.println("Comparing \"" + s1 + "\" to \"" + s2 + "\"...");

        int comparisonResult = s1.compareTo(s2);
        System.out.println("The result of the comparison was " + comparisonResult);

        System.out.print("This means that \"" + s1 + "\" ");
        if(comparisonResult < 0){
            System.out.println("lexicographically precedes \"" + s2 + "\".");
        }else if(comparisonResult > 0){
            System.out.println("lexicographically follows \"" + s2 + "\".");
        }else{
            System.out.println("equals \"" + s2 + "\".");
        }
        System.out.println();
    }
}

Here is a live demonstration that shows it works: http://ideone.com/Drikp3

Upvotes: 11

Related Questions