Java基礎(一)字符串之如何比較字符串


在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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM