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

來源:互聯網
上載者:User

標籤: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基礎(一)字串之如何比較字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.