Java學習筆記05--字串

來源:互聯網
上載者:User

標籤:

String類

由字元所組成的一串文字元號被稱之為字串。在java中字串不僅僅是字元數組,而且是String類的一個執行個體,

可以使用String類來構建。字串的每個字元是使用Unicode字元來構建。

Sring對象上的幾個方法:

length() 取得字串的長度
equals() 判斷源字串中的字元是否等於指定字串中的字元
toLowerCase() 轉換字串中的英文字元為小寫
toUpperCase() 轉換字串中的英文字元為大寫

字串的本質是由字元數組所組成,所以使用String類聲明字串後,該字串會具有數組索引的性質。

char charAt(int index) 返回指定索引處的字元
int indexOf(int ch) 返回指定字元第一個找到的索引位置
int indexOf(String str) 返回指定字串第一個找到的索引位置
int lastIndexOf(int ch) 返回指定字元最後一個找到的索引位置
String substring(int beginIndex) 取出指定索引處至字串尾端的子字串
String substring(int beginIndex ,int endIndex) 取出指定索引範圍子字串(包括beginIndex,不包括endIndex)
char[] toCharArray() 將字串轉換為字元數組
public class T {      public static void main(String[] args) { String str = "hello itmyhome"; for(int i=0;i<str.length();i++){ System.out.print(str.charAt(i)); } System.out.println(); System.out.println("第一個o索引位置 : "+str.indexOf("o")); System.out.println("最後一個o索引位置: "+str.lastIndexOf("o")); System.out.println("截取從第6個字元至尾: "+str.substring(6)); System.out.println("截取從第6個至第8個字元:"+str.substring(6, 8)); char charStr[] = str.toCharArray(); for (int i = 0; i < charStr.length; i++) { System.out.print(charStr[i]); } } }

執行結果:

hello itmyhome  第一個o索引位置 : 4  最後一個o索引位置: 11  截取從第6個字元至尾:        itmyhome  截取從第6個至第8個字元:it  hello itmyhome

在構建字串對象時,除了直接在=後使用""來指定字串常數之外,也可以使用字元數組來構建:

char name[] = {‘i‘,‘t‘,‘m‘,‘y‘,‘h‘,‘o‘,‘m‘,‘e‘}; String s = new String(name);

 

不可變字串

在java中使用字串有一個非常重要的規則必須記得,一個字串對象一旦被配置,它的內容就是固定不可變的。

在java中,使用“=”將一個字串對象指定給一個引用名稱,其意義為改變該名稱所引用的對象,

原來被引用的字串對象若沒有其他名稱來引用它,就會在適當的時候被java的“記憶體回收”機制回收。

在java執行時會維護一個String池(Pool),對於一些可以共用的字串對象,

會現在String池中尋找是否存在相同的String內容(字元相同),如果有就直接返回,而不是直接創造一個新的String對象,

以減少記憶體的耗用。如果在程式中使用下面的方式來聲明,則實際上是指向同一個字串對象:

String str1 = "itmyhome"; String str2 = "itmyhome"; System.out.println(str1==str2);

當直接在程式中使用“”來包括一個字串時,該字串就會在String池中。

 

StringBuilder類

參考 http://blog.csdn.net/itmyhome/article/details/7232340

 

分離字串

可以使用String的split()進行分離字串

需注意問題:“.”,“|”,“?”都是逸出字元,必須加“\”

String s1[] = str.split("\\."); String s2[] = str.split("\\|"); String s3[] = str.split("\\?");

如果在一個字串中有多個分隔字元,可以用“|”作為連字號。

String str = "welcome?to!itmyhome bolg";String s[] = str.split("\\?|!");for (int i = 0; i < s.length; i++) { System.out.println(s[i]);}

以?和!作為分隔字元。 


 

著作權聲明:本文採用BY-NC-SA協議進行授權,轉載麥田技術部落格的文章請註明出處

原文地址:http://itmyhome.com/2015/03/java-study-notes-string

Java學習筆記05--字串

聯繫我們

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