本次介紹的String的方法包括:比較內容、大小寫轉換、首碼和尾碼,並給出了一個例子。
比較字串內容兩種形式。形式一如下:方法定義:public boolean equals(Object o)方法描述:比較是否與參數相同,區分大小寫。例如:str.equals(“this”)結果:False形式二如下:方法定義:public boolean equalsIgnoreCase(Object o)方法描述:比較是否與參數相同,不區分大寫小。例如:str.equalsIgnoreCase(“this”)結果:False
大小寫轉換轉換成大寫或者轉換成小寫。轉換成大寫:方法定義:public String toUpperCase()方法描述:把字串中的所有字元都轉換成大寫。例如:str.toUpperCase()結果:THIS IS A TEST!轉換成小寫:方法定義:public String toLowerCase()方法描述:把字串中的所有字元都轉換成小寫。例如:str.toLowerCase()結果:this is a test!
首碼和尾碼判斷字串是否以指定的參數開始或者結尾。判斷首碼:方法定義:public boolean startsWith(String prefix)方法描述:字串是否以參數指定的子串為首碼。例如:str.startsWith(“this”) 結果:true判斷尾碼:方法定義:public boolean endsWith(String suffix)方法描述:字串是否以參數指定的子串為尾碼。例如:str.endsWith(“this”)結果:false【例】判斷一個字串中出現另外一個字串中出現的次數。package ch8; import java.io.DataInputStream; public class StringTest { public static void main(String args[]){ System.out.println("計算第一個字串在第二個字串中出現的次數。"); DataInputStream din = new DataInputStream(System.in); try{ System.out.println("請輸入第一個字串"); String str1 = din.readLine(); System.out.println("請輸入第二個字串"); String str2 = din.readLine(); String str3 = str2.replace(str1,""); int count = (str2.length() - str3.length())/str1.length(); System.out.println(str1+"在"+str2+"中出現的次數為:"+count); }catch(Exception e){ System.out.println(e.toString()); } }}運行結果為:計算第一個字串在第二個字串中出現的次數。請輸入第一個字串ab請輸入第二個字串abcedabsdabajabab在abcedabsdabajab中出現的次數為:4需要注意的是String本身是一個常量,一旦一個字串建立了,它的內容是不能改變的,那麼如何解釋下面的代碼: s1+=s2;這裡並不是把字串s2的內容添加到字串s1的後面,而是新建立了一個字串,內容是s1和s2的串連,然後把s1指向了新建立的這個字串。如果一個字串的內容經常需要變動,不應該使用String,因為在變化的過程中實際上是不斷建立對象的過程,這時候應該使用StringBuffer。 上一次:
第十八講 String用法(上) 下一次:
第二十講 Java基本類型與字串之間的轉換 李緒成 CSDN Blog:http://blog.csdn.net/javaeeteacher 邀請您為好友:http://student.csdn.net/invite.php?u=124362&c=7be8ba2b6f3b6cc5