Comparing strings by their alphabetical order

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

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

Solution 2 - Java

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.

Solution 3 - Java

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
} 

Solution 4 - Java

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

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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.

Solution 8 - Java

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().

Solution 9 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMakkyView Question on Stackoverflow
Solution 1 - JavaBuhbView Answer on Stackoverflow
Solution 2 - JavadogbaneView Answer on Stackoverflow
Solution 3 - JavamdaguerreView Answer on Stackoverflow
Solution 4 - JavaVasiliy SharapovView Answer on Stackoverflow
Solution 5 - JavaOndra ŽižkaView Answer on Stackoverflow
Solution 6 - Javamalik armanView Answer on Stackoverflow
Solution 7 - JavaDonald DuckView Answer on Stackoverflow
Solution 8 - JavaarenaqView Answer on Stackoverflow
Solution 9 - JavaSuraj NayakView Answer on Stackoverflow