使用Java中的equals()和compareTo()方法比较字符串

本文详细介绍了在Java中如何使用equals()和compareTo()方法比较字符串。equals()方法用于检查两个字符串的内容是否完全相同,而compareTo()方法则根据字符串中字符的Unicode值进行比较,返回正数、负数或0。通过示例代码展示了两种方法的具体应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given strings and we have to compare them using equals() and compareTo() method.

给定字符串,我们必须使用equals()和compareTo()方法进行比较。

  • Java string equals() method

    Java字符串equals()方法

    Java string equals() method compares the content of two strings, If all characters are the same, it returns

    Java字符串equals()方法比较两个字符串的内容,如果所有字符都相同,则返回

    true, else it returns false.

    是true ,否则返回false

  • Java string compareTo() method

    Java字符串compareTo()方法

    Java string compareTo() method is called with a string and another string is supplied as an argument, it compares the strings based on the Unicode values of the characters in the strings. It returns a

    使用字符串调用Java字符串compareTo()方法,并提供另一个字符串作为参数,它根据字符串中字符的Unicode值比较字符串。 它返回一个

    positive number, negative number or 0. If both strings have the same content, it returns 0.

    正数负数0 。 如果两个字符串的内容相同,则返回0

Java代码使用equals(),compareTo()和==运算符比较字符串 (Java code to compare the strings using equals(), compareTo() and == operator )

// Comparing Strings with equals() and compareTo() 
// methods in Java

public class Main {
    public static void main(String[] args) {
        //strings
        String str1 = new String("ABC");
        String str2 = new String("PQR");

        //comparing strings using equals() method
        System.out.println(str1.equals(str2));
        System.out.println(str1.equals(str1));

        //comparing strings using == operator 
        System.out.println(str1 == str1);
        System.out.println(str1 == str2);

        //comparing strings using compareTo() method
        System.out.println(str1.compareTo(str1));
        System.out.println(str1.compareTo(str2));
    }
}

Output

输出量

false
true
true
false
0
-15


翻译自: https://www.includehelp.com/java-programs/comparing-strings-with-equals-and-compareto-methods-in-java.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值