0
点赞
收藏
分享

微信扫一扫

Java基础---字符串之如何比较字符串

心智的年轮 2022-01-25 阅读 149

一:compareTo 比较数据的大小

compareTo(string)
compareTo(object string)
compareToIgnoreCase(String)

示例:

/**
 * Java字符串比较大小
 */
public class StringA {
    public static void main(String[] args){
        String str = "String";
        String anotherStr = "string";
        Object objstr = str;
        System.out.println(str.compareTo(anotherStr));
        System.out.println(str.compareToIgnoreCase(anotherStr));
        System.out.println(str.compareTo(objstr.toString()));
    }
}

结果:

-32
0
0

二:使用equals(),“==”方式比较字符串

示例:

public class StringA {
    public static void main(String[] args){
        String s1 = "hello";
        String s2 = "hello";
        String s3 = new String("hello");
        String s4 = new String("hello");
        System.out.println("s1:" + s1);
        System.out.println("s2:" + s2);
        System.out.println("s3:" + s3);
        System.out.println("s4:" + s4);
        System.out.println("----------比较内容是否相等---------------");
        System.out.println(s1.equals(s2));
        System.out.println(s2.equals(s3));
        System.out.println(s3.equals(s4));
        System.out.println("----------比较引用地址是否相等---------------");
        System.out.println(s1 == s2);
        System.out.println(s2 == s3);
        System.out.println(s3 == s4);
    }
}

结果:

s1:hello
s2:hello
s3:hello
s4:hello
----------比较内容是否相等---------------
true
true
true
----------比较引用地址是否相等---------------
true
false
false
举报

相关推荐

0 条评论