java String筆記

來源:互聯網
上載者:User
子串(substring(a,b))

String greeting="Hello";

System.out.println(greeting.substring(0,3));//Hel

substring方法的第二個參數是不想複製的第一個位置。這裡要複製的位置為0、1、2的字元。

此方法的工作方式有一個優點:容易計運算元串的長度。例如s.substring(a,b)的長的為b-a

拼接
與絕大多數程式設計一樣,Java語言允許使用+號串連兩個字串的操作。
String st1=“hello”;
String st2="world";
System.out.println(st1+st2);//helloworld
不可變字串
String類沒有提供修改字串的方法。如果希望將gretting的內容修改為“Help”,不能直接將後兩個字元修改為p(Strings are constant; their values cannot be changed after they are created.)。
檢測字串是否相等
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
public boolean equalsIgnoreCase(String anotherString)
如果要檢測兩個字串是否相等而不區分大小寫,可以使用該方法。
Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length and corresponding characters in the two strings are equal ignoring case. 
一定不能使用==來檢測兩個字串是否相等!這個運算子只能確定兩個字串是否放置在同一個位置上。當然,若果字串放置在同一個位置上,他們必然相等。但是,完全有可能將內容相同的多個字串的拷貝放置在不同的位置上。
String greeting="Hello";/initialize greeting to a string
if(greeting=="Hello")
//probably true
if(greeting.substring(0,3)=="Hel")
//probably false
如果虛擬機器始終將相同的字串共用,就可以使用==運算子來檢測是否相等。而實際上只有字串常量是共用的,而+或substring等操作產生的結果並不是共用的。因此
千萬不要使用==運算子來測試字串的想等性,以免在程式中出現糟糕的bug。表明上看這種bug很像隨機產生的間歇性錯誤。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.