使用 compareTo() 方法比較字串的 Java 程式


compareTo(obj) 方法將此字串與另一個物件進行比較。如果引數是一個與該字串從詞法角度相同的字串,則返回 0 ;如果引數是一個與該字串從詞法角度較大的字串,則返回一個小於 0 的值;如果引數是一個與該字串從詞法角度較小的字串,則返回一個大於 0 的值。

我們有以下兩個字串 −

String str1 = "tom";
String str2 = "tim";

讓我們對它們進行所有返回值的檢查。

if(str1.compareTo(str2) > 0) {
 System.out.println("First string is greater!");
}
if(str1.compareTo(str2) == 0) {
 System.out.println("First string is equal to Second string!");
}
if(str1.compareTo(str2) < 0) {
 System.out.println("Second string is greater!");
}

以下是最終的示例。

示例

 線上演示

public class Demo {
    public static void main(String[] args) {
       String str1 = "tom";
       String str2 = "tim";
       if(str1.compareTo(str2) > 0) {
          System.out.println("First string is greater!");
       }
       if(str1.compareTo(str2) == 0) {
          System.out.println("First string is equal to Second string!");
       }
       if(str1.compareTo(str2) < 0) {
          System.out.println("Second string is greater!");
       }
    }
}

輸出

First string is greater!

讓我們看另一個示例。

示例

 線上演示

public class Demo {
    public static void main(String[] args) {
       String one = "This is demo text!";
       String two = new String("This text is for demo!");
       String three = new String("This is demo line!");
       String four = new String("The line is demo!");
       int res = one.compareTo( two );
       System.out.println(res);
       res = one.compareTo( three );
       System.out.println(res);
       res = one.compareTo( four );
       System.out.println(res);
    }
}

輸出

-11
8
4

更新時間:2020 年 6 月 26 日

115 人次瀏覽

開啟你的 職業之旅

完成本課程並獲得認證

開始學習
廣告