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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值