當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java String compareTo()用法及代碼示例

Java String 類 compareTo() 方法按字典順序將給定字符串與當前字符串進行比較。它返回一個正數、負數或 0。

它根據字符串中每個字符的 Unicode 值比較字符串。

如果第一個字符串按字典順序大於第二個字符串,則返回一個正數(字符值的差異)。如果第一個字符串在字典上小於第二個字符串,則返回負數,如果第一個字符串在字典上等於第二個字符串,則返回 0。

if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0

用法

public int compareTo(String anotherString)

該方法接受一個 String 類型的參數,該參數將與當前字符串進行比較。

它返回一個整數值。它拋出以下兩個異常:

ClassCastException:如果此對象無法與指定的對象進行比較。

NullPointerException:如果指定的對象為空。

內部實現

int compareTo(String anotherString) {
    int length1 = value.length;
    int length2 = anotherString.value.length;
    int limit = Math.min(length1, length2);
    char v1[] = value;
    char v2[] = anotherString.value;
 
    int i = 0;
    while (i < limit) {
        char ch1 = v1[i];
        char ch2 = v2[i];
        if (ch1 != ch2) {
            return ch1 - ch2;
        }
        i++;
    }
    return length1 - length2;
}

Java 字符串 compareTo() 方法示例

文件名:CompareToExample.java

public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}

輸出:

0
-5
-1
2

Java 字符串 compareTo():空字符串

當我們比較第一個或第二個字符串為空的兩個字符串時,該方法返回字符串的長度。所以,可能有兩種情況:

  • 如果第一個字符串是空字符串,則該方法返回負數
  • 如果第二個字符串是空字符串,則該方法返回一個正數,即第一個字符串的長度。

文件名:CompareToExample2.java

public class CompareToExample2{
public static void main(String args[]){
String s1="hello";
String s2="";
String s3="me";
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
}}

輸出:

5
-2

Java 字符串 compareTo():區分大小寫

為了檢查 compareTo() 方法是否考慮字符的大小寫敏感,我們將在相同序列中包含相同字母的兩個字符串之間進行比較。

假設一個字符串的字母為大寫,第二個字符串的字母為小寫。在比較這兩個字符串時,如果結果為 0,則 compareTo() 方法不考慮字符的大小寫敏感;否則,該方法會考慮字符的大小寫敏感度。

文件名:CompareToExample3.java

public class CompareToExample3
{
// main method
public static void main(String argvs[])
{

// input string in uppercase
String st1 = new String("INDIA IS MY COUNTRY");

// input string in lowercase
String st2 = new String("india is my country");

System.out.println(st1.compareTo(st2));
}
}

輸出:

-32

結論:通過查看輸出很明顯結果不等於零。因此,compareTo() 方法負責字符的大小寫敏感。

Java 字符串 compareTo():ClassCastException

當比較不兼容類型的對象時,拋出 ClassCastException。在以下示例中,我們將 ArrayList (al) 的對象與字符串文字 ("Sehwag") 進行比較。

文件名:CompareToExample4.java

// import statement
import java.util.*;

class Players 
{
     
private String name;

// constructor of the class
public Players(String str)
{
name = str;
}
 
}

public class CompareToExample4
{
 
// main method
public static void main(String[] args) 
{
 
Players ronaldo = new Players("Ronaldo");
Players sachin = new Players("Sachin");
Players messi = new Players("Messi");
ArrayList<Players> al = new ArrayList<>();

al.add(ronaldo);
al.add(sachin);
al.add(messi);
 
// performing binary search on the list al
Collections.binarySearch(al, "Sehwag", null);
}
     
}

輸出:

Exception in thread "main" java.lang.ClassCastException:class Players cannot be cast to class java.lang.Comparable

Java 字符串 compareTo():NullPointerException

當空對象調用 compareTo() 方法時拋出 NullPointerException。觀察以下示例。

文件名:CompareToExample5.java

public class CompareToExample5
{
// main method
public static void main(String[] args) 
{
 
String str = null;

// null is invoking the compareTo method. Hence, the NullPointerException
// will be raised
int no =  str.compareTo("India is my country.");

System.out.println(no);
}
}

輸出:

Exception in thread "main" java.lang.NullPointerException
	at CompareToExample5.main(CompareToExample5.java:9)




相關用法


注:本文由純淨天空篩選整理自 Java String compareTo()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。