Java中字符串如何比較字符串

Java爲我們提供了compareTo、“==”、equals對字符串進行比較,下面介紹一下他們的區別。
示例一:compareTo比較數據的大小

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

該示例通過使用上面的函數比較兩個字符串,並返回一個int類型。若字符串等於參數字符串、則返回0,字符串小於參數字符串、則返回值小於0,字符串大於參數字符串、返回值大於0。

判斷字符串大小的依據是根據他們在字典中的順序決定的。

package com.de.test;

/**
 * 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(),“==”方式比較字符串

使用equals()和==,區別在於equals比較的是內容是否相等、==比較的是引用的變量地址是否相等。

package com.de.test;

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章