字符串詳解

一.字符串入門

1.字符串創建對象的方式:

(1) String str = "hello";

這種方式創建字符串的時候,Jvm首先會檢查字符串常量池中是否存在該字符串的對象,如果已經存在,那麼就不會在字符串常量池中再創建了,直接返回該字符串在字符串常量池中的內存地址;如果該字符串在字符串常量池中並不存在,那麼就會在字符串常量池中先創建該字符串的對象,然後再返回。

(2) new String("hello");

這種方式創建字符串對象的時候,Jvm首先會檢查字符串常量池中是否存在“hello”的字符串,如果已經存在,則不會在字符串常量池中創建了;如果還沒有存在,那麼就會在字符串常量池中創建“hello”字符串對象,然後還會去堆內存中再創建一份字符串的對象,把字符串常量池中的"hello字符串內容拷貝到堆內存中的字符串對象,然後返回堆內存中字符串對象的內存地址。

2.實例一

(1) 實例:

public class Demo1 {
	public static void main(String[] args) {
		String str1 = "hello";
		String str2 = "hello";
		String str3 = new String("hello");
		String str4 = new String("hello");
		System.out.println("str1==str2?"+(str1==str2));  // true  
		System.out.println("str2==str3?"+(str2==str3));  //false
		System.out.println("str3==str4?"+(str3==str4));  // false
		System.out.println("str3.equals(str4)?"+(str3.equals(str4))); //true
	}
}

(2) 運行結果:


(3) 分析:


①首先會在棧內存中聲明一個變量str1,然後用雙引號引起創建字符串的對象,這時候Jvm就會檢查字符串常量池中是否有hello,沒有的話就會在字符串常量池中先創建這個對象,然後把這個對象的內存地址返回給str1,假設它的內存地址是0x97,這時候返回給str1的就是0x97,這時候str1是指向了內存地址爲0x97所存儲的字符串對象。

②然後又聲明瞭一個變量str2,用雙引號引起創建字符串的對象,這時候Jvm就會檢查字符串常量池中是否有hello,發現字符串常量池中已經有了hello,那麼就不會在字符串常量池中再創建了。直接把字符串常量池中hello的內存地址返回給這個變量就可以,也就是說str2記錄的內存地址也是0x97.所以現在str1和str2指向的是同一個對象,所以運行結果爲true。

③首先在棧內存中聲明一個變量str3,當new String的時候,裏面有一個雙引號引起來的字符串,有雙引號引起來的都會先到字符串常量池中先檢查,Jvm在字符串常量池中檢查的時候發現已經存在hello,就不會在字符串常量池中再創建了,接着有個new關鍵字,凡是遇到new關鍵字,Jvm都會在堆內存中開闢一塊新的內存空間,這時候會在堆內存中創建一個堆內存的對象,接着會把字符串常量池中的hello的內容拷貝到堆內存創建的對象中去,接着會把堆內存的內存地址返回給str3,比如說它的內存地址是0x78,str3記錄的則是0x78的內存地址,它指向的是堆內存中創建的對象的內存地址。

④在棧內存中聲明一個變量str4,字符串常量池中有hello,那麼就不會再創建,會到堆內存中創建一個字符串對象,把字符串常量池中的內容拷貝到堆內存中創建的對象中,比如說它的內存地址是0x76,這時候棧內存中str4記錄的就是0x76內存地址所存儲的對象。

(4) 疑問:str3和str4的內存地址並不一樣,爲什麼運行結果返回的是true?

雖然equals方法默認情況下(注意是默認)比較的是兩個對象的內存地址,而現在用到的是字符串的對象,那麼我們就不允許字符串的類對equals方法進行重寫嗎?字符串也可以重寫equals方法,重寫後就可以不遵循默認的情況,因爲看的是String中有沒有重寫equals方法,所以應該查看String的源代碼,查看String的源代碼後我們發現,重寫後的equals方法比較的是兩個字符串對應的字符是否一致。

3.爲什麼比較字符串的時候建議使用equals而不是==號?

因爲==號比較的是內存地址,但是我們在現實開發中一般都是比較內容是否一致,所以就不建議使用==號,如果使用==號,str2和str3就會是false,使用equals,只要兩個字符串的內容一致那麼返回的結果都是一致的。

注意:"=="用於比較 引用數據類型數據的時候比較的是兩個對象的內存地址,equals方法默認情況下比較的也是兩個對象的內存地址。

4. new String("abc")創建了幾個對象?

創建了兩個對象,一個對象是位於字符串常量池中,一個對象是位於堆內存中。

5.實例二

(1) 實例:

public class Demo2 {
	public static void main(String[] args) {
		test(null);
	}
	public static void test(String str){
		if(str.equals("中國"))
		{
			System.out.println("回答正確");
		}else{
			System.out.println("回答錯誤");
		}
	}
}

(2) 運行結果:


(3) 分析:

首先str.equals("中國")運行後就會報空指針異常,如何避免這種錯誤?

那麼就需要使用"中國".equals(str),這也是最簡便的一種方式,調換位置後,"中國"是個常量,也就是這個常量在調用equals方法,這樣就變成了常量是這個方法的調用者,變量作爲參數這樣就可以避免永遠都不會出現空指針異常。因爲如果函數的調用者是一個變量,這個變量有可能指向一個空的對象;如果函數的調用者是一個常量,常量不可能爲空,永遠都不可能爲空也就不會出現空指針異常。這是一個編程習慣,使用equals方法時,我們一般都會讓常量作爲這個方法的調用者,這樣就可以避免空指針異常的出現。

(4) 修改後的實例:

public class Demo3 {
	public static void main(String[] args) {
		test(null);
	}
	public static void test(String str){
		if("中國".equals("str"))
		{
			System.out.println("回答正確");
		}else{
			System.out.println("回答錯誤");
		}
	}
}

(5) 運行結果:


二.String類的構造方法

注意:使用字節數組或者字符數組都可以構建一個字符串對象。

1.String();

(1) 該方法用於創建一個空內容的字符串對象。

(2) 實例:

//String類的無參的構造方法。
public class Demo4 {
	public static void main(String[] args) {
		String str = new String();//調用String類的無參的構造方法,相當於String str = " ";
		System.out.println("字符串的內容是:"+str);
	}
}

(3) 運行結果:


2.String(byte[] bytes) ;

(1) 該方法用於使用一個字節數組構建一個字符串對象;

(2) 實例:

//String(byte[] bytes)  使用一個字節數組構建一個字符串對象
public class Demo5 {
	public static void main(String[] args) {
		byte[] buf = {97,98,99};//這些字節數組裏存儲的都是那些字符對應的碼值
		String str = new String(buf); //使用一個字節數組構建一個字符串對象
		System.out.println("字符串的內容:"+str);
	}
}

(3) 運行結果:


3.String(byte[] bytes, int offset, int length) 

(1) 參數詳解:  

bytes:要解碼的數組(解碼就是把數字轉換成數字代表的字符)

offset:指定從數組中那個索引值開始解碼。也就是說從字節數組中的哪一位開始查找對應的字符。
length:要解碼多少個元素。也就是要查找多少個字符。

(2) 實例

public class Demo6 {
	public static void main(String[] args) {
		byte[] buf = {97,98,99};
		String str = new String(buf,1,2);//使用一個字節數組構建一個字符串對象,指定開始解碼的索引值和解碼的個數 
		System.out.println("字符串的內容:"+str);
	}
}

(3) 運行結果:


4.String(char[] value);  

(1) 使用一個字符數組構建一個字符串。

(2) 實例:

//String(char[] value)  使用一個字符數組構建一個字符串。	
public class Demo7 {
	public static void main(String[] args) {
		char[] arr = {'馬','上','畢','業','了'};
		String str = new String(arr); //使用字符數組構建一個字符串
		System.out.println("字符串的內容:"+str);
	}
}

(3) 運行結果:


5.String(char[] value, int offset, int count);  

(1) 使用一個字符數組構建一個字符串, 指定開始的索引值,與使用字符個數。

(2) 實例:

public class Demo8 {
	public static void main(String[] args) {
		char[] arr = {'馬','上','畢','業','了'};
		String str = new String(arr,2,2); 
		System.out.println("字符串的內容:"+str);
	}
}

(3) 運行結果:


6.String(int[] codePoints,int offset,int count);

(1) 實例:

public class Demo9 {
	public static void main(String[] args) {
		int[] buf = {65,66,67};
		String str = new String(buf,0,3);
		System.out.println("字符串的內容:"+str);
	}
}

(2) 運行結果:


三.String類的普通常用方法

1.獲取的方法

(1) 方法:

①int length():該方法用於獲取字符串的長度。

②char charAt(int index):傳入一個索引值,根據索引值獲取特定位置的字符 (注意角標越界)。

③int indexOf(String str):查找子串第一次出現的索引值,如果子串沒有出現在字符串中,那麼則返回-1表示。

④int lastIndexOf(String str):查找子串最後一次出現的索引值 , 如果子串沒有出現在字符串中,那麼則返回-1表示。

(2) 實例:

public class Demo3 {
	public static void main(String[] args) {
		String str = "abc你好ab你好";
		System.out.println("字符串的字符個數:" + str.length());
		System.out.println("根據索引值獲取對應的字符:"+ str.charAt(3));
		System.out.println("查找子串第一次出現的索引值:" + str.indexOf("你好"));
		System.out.println("查找子串最後一次出現的索引值:" + str.lastIndexOf("你好"));	
	}
}

(3) 運行結果:


2.判斷的方法

(1) 方法:

①boolean endsWith(String str):判斷是否以指定字符串結束。
②boolean isEmpty():判斷長度是否爲0,也就是判斷字符串是否爲空內容。
③boolean contains(CharSequences):判斷是否包含指定序列,該方法可以應用於搜索。
④boolean equals(Object anObject):判斷是否相等,判斷兩個字符串的內容是否一致。是區分大小寫的。

⑤boolean equalsIgnoreCase(String anotherString) 忽略大小寫是否相等,驗證碼都是忽略大小寫的

(2) 實例:

public class Demo11 {
	public static void main(String[] args) {
		String str = "Demo.java";
		System.out.println("是否以指定 的字符串結束:"+ str.endsWith("java"));
		System.out.println("是否以指定 的字符串結束:"+ str.endsWith("va"));
		System.out.println("是否以指定 的字符串結束:"+ str.endsWith("ja"));
		
		System.out.println("判斷字符串是否爲空內容:"+str.isEmpty());
		System.out.println("判斷字符串是否包含指定的內容:"+ str.contains("Demo"));
		System.out.println("判斷兩個 字符串的內容是否一致:"+ "DEMO.JAVA".equals(str));
		System.out.println("判斷兩個字符串的內容是否一致(忽略大小寫比較):"+ "DEMO.JAVA".equalsIgnoreCase(str));
	}
}

(3) 運行結果:


3.轉換的方法

注意:字節數組與字符數組、字符串他們三者之間是可以互相轉換的。

(1) 方法:

①char[] toCharArray() :將字符串轉換爲字符數組。

②byte[] getBytes():將字符串轉換爲字節數組。

(2) 實例:

import java.util.Arrays;
public class Demo12 {
	public static void main(String[] args) {
		String str = "Demo.java";
		char[] buf = str.toCharArray();  //把字符串轉換字符數組
		System.out.println("字符數組:"+ Arrays.toString(buf));
		byte[] buf2 = str.getBytes();	//把字符串轉字節數組
		System.out.println("字節數組:"+ Arrays.toString(buf2));
	}
}

(3) 運行結果:


4.其他的方法

注意:CharSequence是一個接口,而String類是它的實現類。

(1) 方法:

①String replace(String oldChar, String newChar):替換。

②String[] split(String regex):切割。
③String substring(int beginIndex):指定開始的索引值截取子串。
④String substring(int beginIndex, int endIndex):指定開始與結束的索引值截取子串。
⑤String toUpperCase():轉大寫。
⑥String toLowerCase():轉小寫。

⑦String trim():去除字符串首尾的空格。

(2) 實例

public class Demo5 {	
	public static void main(String[] args) {
		String str = "我們不學習";
		System.out.println("指定新內容替換舊 的內容:"+ str.replace("不", "要好好"));
		str = "我們要-好-好-學-習";//切成5份
		String[] arr = str.split("-"); //根據指定的字符進行切割 。
		System.out.println("字符串數組的內容:"+ Arrays.toString(arr));
		str = "馬上要畢業了";
		System.out.println("指定開始的索引值截取子串:"+ str.substring(2));
		System.out.println("指定開始與結束的索引值截取子串:"+ str.substring(2,6)); //方法重載,包頭不包尾  注意:截取的內容是包括開始的索引值,不包括結束的索引值, 截取的位置是結束的索引值-1.
		//注意,凡是Java方法中出現開始和結束的索引值,都是遵循包頭不包尾
		str = "abC中國";
		System.out.println("轉大寫:" + str.toUpperCase());
		str = "AbdfSDD"; 
		System.out.println("轉小寫:"+ str.toLowerCase());
		str = "         我們要        努力學習            ";
		System.out.println("去除字符串首尾的空格:"+ str.trim());
	}
}

(3) 運行結果:


四.字符串實例:

1.實例一

(1) 需求:自己實現trim的方法。

(2) 分析:只要我們能確定開始StartIndex和結束endIndex這兩個位置的索引值,那麼這個題目我們就能做出來。最關鍵的是這兩個索引值應該如何確定?把這兩個變量定義成這個字符串開始與結束的位置,首先用startIndex確定是否是空字符,是的話就前進一步,結束的索引值也要判斷是否是空字符。是的話就後退一步。

(3) 實例:

public class Demo1 {
	public static void main(String[] args) {
		String str  ="        我們        快要畢業了             ";	
		System.out.println(myTrim(str));
	}
	public static String myTrim(String str){
		//先轉換成字符 數組
		char[] arr = str.toCharArray();
		//定義兩個 變量記錄開始與結束 的索引值
		int startIndex = 0 ;
		int endIndex = arr.length -1;
		//確定開始 的索引值
		while(true){
			if(arr[startIndex]==' '){
				startIndex++;
			}else{
				break;
			}
		}
		//確定結束 的索引值:
		while(true){
			if(arr[endIndex]==' '){
				endIndex--;
			}else{
				break;
			}
		}
		//截取子串返回
		return str.substring(startIndex,endIndex+1);		
	}
}

(4) 運行結果:


2.實例二

(1) 需求:

獲取上傳文件名  "D:\\20180225\\day01\\Demo1.java"。從字符串中獲取文件名爲Demo1.java。

(2) 分析:

可以用切割的方法,按照"\\"來進行切割,把它分割成好幾部分,返回一個字符串的數組,只獲取字符串數組的最後一個就可以了;也可以用截取的方法,只要能確定D的索引值就可以了。那麼如何確定D的索引值?也就是最後"\\"的索引值+1就是D的索引值。

(3) 實例:

public class Demo2 {
	public static void main(String[] args) {
		String str =  "D:\\20180225\\day01\\Demo1.java";
		getFileName(str);
	}
	public static void getFileName(String path){
		int index = path.lastIndexOf("\\");//轉義
		String fileName = path.substring(index+1);
		System.out.println("文件名:"+ fileName);
	}
}

(4) 運行結果:


3.實例三

(1) 需求:

將字符串對象中存儲的字符反序。例如:新中國好 -----> 好國中新。

(2) 分析:

只需要把它轉換成一個字符數組,轉成字符數組後就可以定義兩個索引值,一個是開始的索引值startIndex,另一個是結束的索引值endIndex,這兩個交換後,startIndex向前++,endIndex向後--,再繼續進行交換,(要定義兩個變量記錄要交換位置的索引值,只要startIndex<endIndex那麼就進行交換),當這個字符數組被反轉後,我們只需要再使用這個字符數組構建一個字符串即可。

(3) 實例:

public class Demo3 {
	public static void main(String[] args) {
		String str = "新中國好";
		System.out.println("翻轉後的字符串:"+ reverse(str));
	}
	public static String reverse(String str){
		char[] arr = str.toCharArray();
		for(int startIndex = 0 , endIndex=arr.length-1 ; startIndex<endIndex; startIndex++,endIndex--){
				char temp = arr[startIndex];
				arr[startIndex] = arr[endIndex];
				arr[endIndex] = temp;
		}
		//使用字符數組構建一個字符串。
		return new String(arr);
	}
}

(4) 運行結果


4.實例四

(1) 需求:

求一個子串在整串中出現的次數 。

(2) 分析:

先定義一個變量記錄出現的次數,count = 0;接着定義一個變量用於記錄開始尋找的索引值的位置,int fromIndex = 0;首先從索引值爲0的地方開始找,找到第一個Java後,count++,然後繼續開始向後尋找,第一次找到Java的索引值是3,第二次是從java後的a開始繼續往後找,而這個a的索引值是7,那麼第二次的fromIndex應該怎麼計算出來?首先確定第一次java的索引值爲3,接着java的長度是4,所以第二次從a的索引值7開始找。

(3) 實例:

public class Demo4 {
	public static void main(String[] args) {
		String str = "abcjavaabcjavaphpjava";  //統計java在這個字符串中出現的次數
		getCount(str, "java");
	}
	//統計子串出現 的次數
	public static void getCount(String str,String target){
		int count = 0 ; //用於記錄出現的次數
		int fromIndex  = 0; // 記錄從那個索引值開始尋找目標子串
		while((fromIndex = str.indexOf(target, fromIndex))!=-1){
			//如果indexof方法返回 的不是-1,那麼就是已經找到了目標 元素。
			//如果這個方法返回的是-1意味着再往後找就沒有了,所以循環的結束條件是隻要不等於-1就繼續往後找。
			//indexOf會返回一個索引值,找到之後會有一個返回值,比如返回3,那麼就應該用fromIndex來記錄它。
			//因爲下次開始尋找的位置是
			count++;
			fromIndex = fromIndex+target.length();
		}
		System.out.println("出現的次數:"+ count);
	}
}

(4)  運行結果:


五.StringBuffer類

1.前言

(1) 字符串的特點:字符串是常量,它們的值在創建之後不能更改。

(2) 字符串的內容一旦發生了變化,那麼馬上會創建一個新的對象。

(3) 實例:

public class Demo1 {
	public static void main(String[] args) {
		String str1 = "hello";
		String str2	= str1+" world";
		System.out.println("str1與str2是同一個 對象嗎?"+(str1==str2));
	}
}

運行結果如下圖所示:


2.StringBuffer類: 

(1) 字符串的內容不適宜頻繁修改,因爲一旦修改馬上就會創建一個新的對象。如果不斷頻繁修改,在內存中就會有很多的字符串對象存在。如果需要頻繁修改字符串的內容,建議使用字符串緩衝類(StringBuffer)。

(2) StringBuffer 是字符串的緩衝區,其實就是一個存儲字符的容器,用它對字符串進行增刪查改會非常方便。

(3) 疑問:使用Stringbuffer無參的構造函數創建 一個對象時,默認的初始容量是多少?如果長度不夠使用了,自動增長多少倍?

通過查看源代碼我們發現,StringBuffer 底層是依賴了一個字符數組才能存儲字符數據的,該字符串數組默認 的初始容量是16, 如果字符數組的長度不夠使用時,自動增長1倍,也就是是原來的2倍。

(4) 實例

public class Demo2 {
	public static void main(String[] args) {
		//先使用StringBuffer無參的構造函數創建一個字符串緩衝類。
		StringBuffer sb = new StringBuffer(); 
		sb.append("java");
		sb.append("java");
		sb.append("java");
		sb.append("java");
		sb.append("java");
		System.out.println(sb);//其初始容量爲16個字符,但是爲什麼可以輸出20個字符。		
	}
}

運行結果如下圖所示:


3.StringBuffer類具備的方法:

(1) 增加的方法:

①append(boolean b) :有很多重載的方法,可以添加任意類型的數據到容器中。

package stringbuffer;
public class append {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		//添加的方法
		sb.append("abc");
		sb.append(true);//把true變成字符串輸出
		sb.append(3.14f);
		System.out.println("字符串緩衝類的內容:"+sb);
	}
}

運行結果如下圖所示:


②insert(int offset, boolean b):指定插入的索引值,插入對應的內容

public class insert {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		//插入的方法
		sb.append("abc");
		sb.insert(2,"小明");//在b和c之間插入小明,因爲b和c之間的索引值是2.
		System.out.println("字符串緩衝類的內容:"+sb);
	}
}

運行結果如下圖所示:


(2) 刪除的方法

①delete(int start, int end):根據指定的開始與結束的索引值刪除對應的內容。

public class delete {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		System.out.println("執行刪除操作前:"+sb);
		//刪除的方法
		sb.delete(2, 4);//刪除小明,刪除的時候也是包頭不包尾的。
		System.out.println("執行刪除操作後:"+sb);
	}
}

運行結果如下圖所示:


②deleteCharAt(int index):根據指定 的索引值刪除一個字符。

public class deleteCharAt {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		System.out.println("執行刪除操作前:"+sb);
		//刪除
		sb.deleteCharAt(3);//刪除"明"
		System.out.println("執行刪除操作後:"+sb);
	}
}

運行結果如下圖所示:


(3) 修改的方法

①replace(int start, int end, String str):根據指定 的開始與結束索引值替代成指定的內容。

public class replace {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		System.out.println("執行替換操作前:"+sb);
		//替換
		sb.replace(2,4,"張三");//把小明替換成張三
		System.out.println("執行替換操作後:"+sb);
	}
}

運行結果如下圖所示:


②reverse():反轉字符串緩衝類的內容。abc--->cba

public class reverse {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		System.out.println("執行反轉操作前:"+sb);
		//反轉字符串的內容
		sb.reverse();
		System.out.println("執行反轉操作後:"+sb);
	}
}

運行結果如下圖所示:


③setCharAt(int index, char ch):把指定索引值的字符替換成指定的字符。 

public class setCharAt {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		System.out.println("執行替換操作前:"+sb);
		//替換單個字符
		sb.setCharAt(3, '紅');//把'明'替換成'紅'
		System.out.println("執行替換操作後:"+sb);
	}
}

運行結果如下圖所示:


④substring(int start, int end):根據指定的索引值截取子串。

public class substring {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		//截取小明
		String subString = sb.substring(2, 4);//返回類型是String類型
		System.out.println("子串的內容:"+subString);
	}
}

運行結果如下圖所示:


⑤ensureCapacity(int minimumCapacity):指定StringBuffer內部的字符數組長度的。基本很少用到。

如果想指定字符數組的初始容量可以使用帶參的構造方法來指定。

public class ensureCapacity {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abc");
		sb.insert(2,"小明");
		sb.ensureCapacity(20);//指定字符數組的長度爲20,默認是16
	}
}

(4) 查看的方法

①indexOf(String str, int fromIndex):查找指定的字符串第一次出現的索引值,並且指定開始查找的位置。

public class indexOf {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abcjavaabc");
		int index = sb.indexOf("java", 0);//從索引值爲0的位置開始找
		System.out.println("返回的索引值爲:"+index);
	}
}

運行結果如下圖所示:


②capacity():查看當前字符數組的長度。 

public class capacity {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abcjavaabc");
		//查看當前字符數組的長度
		System.out.println("當前字符數組的長度是:"+sb.capacity());//16
		sb.append("javajava");//此時存儲了18個字符,那麼這時候當前字符數組的長度又是多少?
		System.out.println("當前字符數組的長度是:"+sb.capacity());//34,因爲字符串的長度會增長一倍+2
	}
}

運行結果如下圖所示:


③length():查看存儲字符的個數。

public class length {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abcjavaabc");
		sb.append("javajava");
		System.out.println("查看當前字符數組存儲字符的個數:"+sb.length());
	}
}

運行結果如下圖所示:


④charAt(int index):根據指定的索引值查找字符

public class charAt {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abcjavaabc");
		sb.append("javajava");
		System.out.println("根據指定的索引值查找字符:"+sb.charAt(2));
	}
}

運行結果如下圖所示:


⑤toString():把字符串緩衝類的內容轉成字符串返回。

現在stringBuffer裏存儲了很多的字符數據,假設有一個test方法,這個方法是要接收一個字符串的,而字符的內容是存儲在StringBuffer裏的。而現在調用這個test方法應該如何調用呢?首先肯定不能把sb傳進去,因爲類型不一樣,如何把這個容器中存儲的字符轉換成字符串呢?可以用sb.toString()方法,這樣就會把裏面存儲的內容,以字符串的形式返回。

public class toString {
	public static void main(String[] args) {
		StringBuffer sb = new StringBuffer();
		sb.append("abcjavaabc");
		sb.append("javajava");
		String content = sb.toString();
		test(content);
	}
	public static void test(String str){
		System.out.println("字符串緩衝類的內容是:"+str);
	}
}

運行結果如下圖所示:


六.StringBuilder類

1.StringBuffer 與 StringBuilder的相同處與不同處:

(1) 相同點:
①兩個類都是字符串緩衝類。
②兩個類的方法都是一致的。(只要是StringBuffer有的方法,StringBuilder一樣有)
(2) 不同點:
①StringBuffer是線程安全的,操作效率低 ,StringBuilder是線程非安全的,操作效率高。
(所謂的安全是指在一個時間段裏只會允許一個線程來操作這份代碼,而線程不安全是指在一個時間段裏一份代碼可以由多個線程來執行)
②StringBuffer是jdk1.0出現 的,StringBuilder 是jdk1.5的時候出現的。

2.推薦使用:StringBuilder,因爲操作效率高



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章