当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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


Java 中的字符串是仅由数组内部支持的对象,这意味着为字符分配连续的内存。请注意,字符串在 Java 中是不可变的,这意味着一旦我们创建了 String 对象并为其分配了一些值,我们就无法更改其内容。但是,我们可以根据需要进行修改来创建另一个 String 对象。

Java的String类包含许多对字符串执行各种操作的方法,我们将重点关注Java StringcompareTo()本文中的方法。

Java String.compareTo()方法

Java compareTo()方法将给定字符串与当前字符串进行比较按字典顺序。它返回正数、负数或 0。它根据统一码值字符串中的每个字符。

例子:

Java


public class StringCompareTo {
    public static void main(String[] args) {
        String str1 = "Geeks";
        String str2 = "Geeks";
        int comparison = str1.compareTo(str2);
        if (comparison < 0) {
            System.out.println(str1 + " comes before " + str2 + " lexicographically.");
        } else if (comparison > 0) {
            System.out.println(str1 + " comes after " + str2 + " lexicographically.");
        } else {
            System.out.println(str1 + " and " + str2 + " are lexicographically equal.");
        }
    }
}

输出:

Geeks and Geeks are lexicographically equal.

用法

int comparison = str1.compareTo(str2);

参数:

  • str1: 用于比较的字符串 1
  • str2:用于比较的字符串 2

返回:

  • 如果字符串 1 > 字符串 2,它返回积极的数字
  • 如果字符串 1 < 字符串 2,它返回消极的数字
  • 如果字符串1==字符串2,它返回0

异常:它抛出以下两个异常:

  • NullPointerException -如果指定的对象为 Null。
  • ClassCastException-如果当前对象无法与指定对象进行比较。

CompareTo()方法的变体

三种变体compareTo()其方法如下:

  1. 使用intcompareTo(对象obj)
  2. 使用intcompareTo(String AnotherString)
  3. 使用intcompareToIgnoreCase(String str)

1.intcompareTo(对象 obj)

此方法将此字符串与另一个对象进行比较。

句法:

int compareTo(Object obj)

参数:

obj:  the Object to be compared.

返回值:如果参数是按字典顺序等于该字符串的字符串,则值为 0;如果参数是按字典顺序大于此字符串的字符串,则为小于 0 的值;如果参数是按字典顺序小于此字符串的字符串,则为大于 0 的值。

例子:

下面是intcompareTo(Object obj)的实现:

Java


// Java code to demonstrate the
// working of compareTo()
public class Cmp1 {
    public static void main(String args[])
    {
        // Initializing Strings
        String str1 = "geeksforgeeks";
        String str2 = new String("geeksforgeeks");
        String str3 = new String("astha");
        // Checking if geeksforgeeks string
        // equates to geeksforgeeks object
        System.out.print(
            "Difference of geeksforgeeks(obj) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str2));
        // Checking if geeksforgeeks string
        // equates to astha object
        System.out.print(
            "Difference of astha(obj) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str3));
    }
}
输出
Difference of geeksforgeeks(obj) and geeksforgeeks(str) : 0
Difference of astha(obj) and geeksforgeeks(str) : 6



2.intcompareTo(String anotherString)

此方法按字典顺序比较两个字符串。

句法:

int compareTo(String anotherString)

参数:

anotherString:  the String to be compared.

返回值:如果参数是按字典顺序等于该字符串的字符串,则值为 0;如果参数是按字典顺序大于此字符串的字符串,则为小于 0 的值;如果参数是按字典顺序小于此字符串的字符串,则为大于 0 的值。

例子:

下面是intcompareTo(String anotherString)的实现:

Java


// Java code to demonstrate the
// working of compareTo()
public class Cmp2 {
    public static void main(String args[])
    {
        // Initializing Strings
        String str1 = "geeksforgeeks";
        String str2 = "geeksforgeeks";
        String str3 = "astha";
        // Checking if geeksforgeeks string
        // equates to geeksforgeeks string
        System.out.print(
            "Difference of geeksforgeeks(str) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str2));
        // Checking if geeksforgeeks string
        // equates to astha string
        System.out.print(
            "Difference of astha(str) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str3));
    }
}
输出
Difference of geeksforgeeks(str) and geeksforgeeks(str) : 0
Difference of astha(str) and geeksforgeeks(str) : 6



3.intcompareToIgnoreCase(String str)

此方法按字典顺序比较两个字符串,忽略大小写差异。

用法:

int compareToIgnoreCase(String str)

参数:

str: the String to be compared.

返回值:当指定的 String 大于、等于或小于此 String 时,此方法返回负整数、零或正整数,忽略大小写。

例子:

下面是intcompareToIgnoreCase(String str)的实现:

Java


// Java code to demonstrate the
// working of compareToIgnoreCase()
public class Cmp3 {
    public static void main(String args[])
    {
        // Initializing Strings
        String str1 = "geeks";
        String str2 = "gEEkS";
        // Checking if geeksforgeeks string
        // equates to geeksforgeeks string
        // case sensitive
        System.out.print(
            "Difference of geeks and gEEkS (case sensitive) : ");
        System.out.println(str1.compareTo(str2));
        // Checking if geeksforgeeks string
        // equates to astha string
        // case insensitive
        // using compareToIgnoreCase()
        System.out.print(
            "Difference of geeks and gEEkS (case insensitive) : ");
        System.out.println(str1.compareToIgnoreCase(str2));
    }
}
输出
Difference of geeks and gEEkS (case sensitive) : 32
Difference of geeks and gEEkS (case insensitive) : 0



Java String compareTo() 方法中的异常

Java 中的 compareTo() 方法可能引发两种可能的异常:

  • NullPointerException
  • ClassCastException

compareTo() NullPointerException

在 Java 中,compareTo() 方法会抛出 NullPointerException;如果被比较的任何一个对象是空值。这可确保您显式处理空值并防止意外行为。

例子:

Java


public class cmp5  
{  
// 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("Geeks");  
   
System.out.println(no);  
}  
}

输出:

Exception in thread "main" java.lang.NullPointerException
    at cmp5.main(cmp5.java:11)

compareTo() ClassCastException

这是一个运行时异常,当在 compareTo() 方法中比较两个不兼容类型的对象时会发生。

例子:

Java


public class ClassCastExceptionExample {
    public static void main(String[] args) {
        Object obj1 = "Hello";
        Object obj2 = 10; // Integer object
        // Explicitly cast obj2 to String to force the exception
        int comparison = ((String) obj2).compareTo(obj1);  
        System.out.println("Comparison: " + comparison); 
    }
}

输出:

./ClassCastExceptionExample.java:8: error: incompatible types: Object cannot be converted to String
        int comparison = ((String) obj2).compareTo(obj1);  // ClassCastException occurs here

Also Read: 

  1. Compare two Strings in Java
  2. Compare two strings lexicographically in Java
  3. Java Integer compareTo() method

结论

Java中的compareTo()函数用于按字典顺序比较两个字符串或对象。它返回正整数、零或负整数。在本教程中,我们介绍了此方法并讨论了其工作原理和异常情况。

阅读更多String

Java String CompareTo() 方法 - 常见问题解答

Java中如何比较字符串?

You can compare strings in Java using the compareTo() method. It accepts two parameters and compare them lexicographically.

Java中compareTo()方法和equals()方法有什么区别?

equals() method compareTo() method
Used to check if two objects are exactly the same. Used to compare two objects and determine their relative order.

Returns a boolean:

  • true if the objects are considered equal.
  • false otherwise.

Returns an integer:

  • Negative value if the first object is considered “less than” the second.
  • Zero if the objects are considered equal.
  • Positive value if the first object is considered “greater than” the second.

Java中compareTo()返回什么?

compareTo() method in Java returns an integer. It can have three possible values:

  • Negative value: When the first object is considered “less than” the second.
  • Zero: When the objects are considered equal.
  • Positive value: When the first object is considered “greater than” the second.


相关用法


注:本文由纯净天空筛选整理自佚名大神的英文原创作品 Java String compareTo() Method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。