標籤:ack equal als false new 等於 使用 參數 span
在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())); }}
執行上面代碼產生下面結果
-3200
樣本二:使用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:hellos2:hellos3:hellos4:hello----------比較內容是否相等---------------truetruetrue----------比較引用地址是否相等---------------truefalsefalse
Java基礎(一)字串之如何比較字串