子串(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很像隨機產生的間歇性錯誤。