Comparing strings by their alphabetical order

前端 未结 7 2170
灰色年华
灰色年华 2020-11-27 04:26
String s1 = \"Project\";
String s2 = \"Sunject\";

I want to compare the two above string by their alphabetic order (which in this case \"Project\"

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-27 04:39

    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

提交回复
热议问题