1、StringBuffer類概述
1)我們如果對字符串進行拼接操作,每次拼接,都會構建一個新的String對象,既耗時,又浪費空間。而StringBuffer就可以解決這個問題
2)線程安全的可變字符序列
3)StringBuffer和String的區別
· 前者長度和內容可變,后者不可變。
· 如果使用前者做字符串的拼接,不會浪費太多的資源。
2、構造方法
· public StringBuffer() :無參構造方法
· public StringBuffer(int capacity) :指定容量的字符串緩沖區對象
· public StringBuffer(String str) :指定字符串內容的字符串緩沖區對象
StringBuffer的方法:
· public int capacity():返回當前容量,理論值
· public int length():返回長度(字符數) ,實際值
public class StringBufferDemo01 { public static void main(String[] args) { // public StringBuffer():無參構造方法 StringBuffer sb = new StringBuffer(); System.out.println("sb:"+sb); System.out.println("sb.capacity:"+sb.capacity()); //16 System.out.println("sb.length:"+sb.length()); //0 System.out.println("--------------------------"); // public StringBuffer(int capacity):指定容量的字符串緩沖區對象 StringBuffer sb2 = new StringBuffer(50); System.out.println("sb2:"+sb2); System.out.println("sb2.capacity:"+sb2.capacity()); //50 System.out.println("sb2.length:"+sb2.length()); //0 System.out.println("--------------------------"); // public StringBuffer(String str):指定字符串內容的字符串緩沖區對象 StringBuffer sb3 = new StringBuffer("hello"); System.out.println("sb3:"+sb3); //"hello" System.out.println("sb3.capacity:"+sb3.capacity()); //21 System.out.println("sb3.length:"+sb3.length());//5 System.out.println("--------------------------"); } }
注意返回值,可以查看源碼,默認空間是16。
/** * Constructs a string buffer with no characters in it and an * initial capacity of 16 characters. */ public StringBuffer() { super(16); } /** * Constructs a string buffer with no characters in it and * the specified initial capacity. * * @param capacity the initial capacity. * @exception NegativeArraySizeException if the <code>capacity</code> * argument is less than <code>0</code>. */ public StringBuffer(int capacity) { super(capacity); } /** * Constructs a string buffer initialized to the contents of the * specified string. The initial capacity of the string buffer is * <code>16</code> plus the length of the string argument. * * @param str the initial contents of the buffer. * @exception NullPointerException if <code>str</code> is <code>null</code> */ public StringBuffer(String str) { super(str.length() + 16); append(str); }
3、StringBuffer類的成員方法
1)添加功能
· public StringBuffer append(String str):可以把任意類型數據添加到字符串緩沖區里面,並返回字符串緩沖區本身
· public StringBuffer insert(int offset,String str):在指定位置把任意類型的數據插入到字符串緩沖區里面,並返回字符串緩沖區本身
public class StringBufferDemo02 { public static void main(String[] args) { // 創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); //返回對象本身 StringBuffer sb2 = sb.append("hello"); System.out.println("sb:"+sb); //sb:hello System.out.println("sb2:"+sb2); //sb2:hello System.out.println(sb == sb2); //true //一步一步的添加數據 StringBuffer sb3 = new StringBuffer(); sb3.append("hello"); sb3.append(true); sb3.append(12); sb3.append(34.56); System.out.println("sb3:"+sb3); //sb3:hellotrue1234.56 //鏈式編程 StringBuffer sb4 = new StringBuffer(); sb4.append("hello").append(true).append(12).append(34.56); System.out.println("sb4:"+sb4); //sb4:hellotrue1234.56 //StringBuffer insert(int offset,Stringstr):插入數據 sb3.insert(5,"hello"); System.out.println("sb3:"+sb3); //sb3:hellohellotrue1234.56 } }
2)刪除功能
· public StringBuffer deleteCharAt(int index):刪除指定位置的字符,並返回本身
· public StringBuffer delete(int start,int end):刪除從指定位置開始指定位置結束的內容,並返回本身
public class StringBufferDemo03 { public static void main(String[] args) { // 創建對象 StringBuffer sb1 = new StringBuffer(); // 創建對象 sb1.append("hello").append("world").append("java"); System.out.println("sb1:"+sb1); //sb1:helloworldjava // public StringBuffer deleteCharAt(int index):刪除指定位置的字符,並返回本身 // 需求:我要刪除e這個字符 sb1.deleteCharAt(1); // 需求:我要刪除第一個l這個字符 sb1.deleteCharAt(1); System.out.println("sb1:"+sb1); //sb1:hloworldjava System.out.println("----------------"); // public StringBuffer delete(int start,int end):刪除從指定位置開始指定位置結束的內容,並返回本身 StringBuffer sb2 = new StringBuffer("Hello World Java"); System.out.println("sb2:"+sb2); //sb2:Hello World Java // 需求:我要刪除World這個字符串 sb2.delete(5,11); System.out.println("sb2:"+sb2); //sb2:Hello Java // 需求:我要刪除所有的數據 sb2.delete(0, sb2.length()); System.out.println("sb2:"+sb2); //sb2: } }
3)替換功能
· public StringBuffer replace(int start,int end,String str):使用給定String中的字符替換詞序列的子字符串中的字符
public class StringBufferDemo04 { public static void main(String[] args) { // 創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); // 添加數據 sb.append("hello"); sb.append("world"); sb.append("java"); System.out.println("sb:" + sb); //sb:helloworldjava // public StringBuffer replace(int start,int end,String str):從start開始到end用str替換 // 需求:我要把world這個數據替換為"節日快樂" sb.replace(5,10,"節日快樂"); System.out.println("sb:"+sb); //sb:hello節日快樂java } }
4)反轉功能
· public StringBuffer reverse():將此字符序列用其反轉形式取代,返回對象本身
public class StringBufferDemo05 { public static void main(String[] args) { //創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); //添加數據 sb.append("林青霞愛我"); System.out.println("sb:"+sb); //sb:林青霞愛我 //public StringBuffer reverse() sb.reverse(); System.out.println("sb:"+sb); //sb:我愛霞青林 } }
5)截取功能
· public String substring(int start):返回一個新的String,它包含此字符序列當前所包含的字符子序列
· public String substring(int start,int end):返回一個新的String,它包含此序列當前所包含的字符子序列
注意:截取功能和前面幾個功能的不同
· 返回值類型是String類型,本身沒有發生改變
public class StringBufferDemo06 { public static void main(String[] args) { //創建字符串緩沖區對象 StringBuffer sb = new StringBuffer(); sb.append("hello").append("world").append("java"); System.out.println("sb:"+sb); //sb:helloworldjava //截取功能 String s = sb.substring(5); System.out.println("s:"+s); //s:worldjava System.out.println("sb:"+sb); //sb:helloworldjava String ss = sb.substring(5,10); System.out.println("ss:"+ss); //ss:world System.out.println("sb:"+sb); //sb:helloworldjava } }
4、練習題:String與StringBuffer的相互轉換
public class StringBufferDemo07 { public static void main(String[] args) { //String --> StringBuffer String s = "hello"; // 注意:不能把字符串的值直接賦值給StringBuffer // StringBuffer sb = "hello"; // StringBuffer sb = s; //方式一:通過構造方法 StringBuffer sb = new StringBuffer(s); //方式二:通過append方法 StringBuffer sb2 = new StringBuffer(); sb2.append(s); System.out.println("sb:"+sb); //sb:hello System.out.println("sb2:"+sb2); //sb2:hello System.out.println("-------------------------"); //StringBuffer --> String StringBuffer buffer = new StringBuffer("java"); //方式一:通過構造方法 String str = new String(buffer); //方式二:通過toString()方法 String str2 = buffer.toString(); System.out.println("str:"+str); //str:java System.out.println("str2:"+str2); //str2:java } }
5、練習題:把數組拼接成一個字符串
public class StringBufferDemo08 { public static void main(String[] args) { //定義一個數組 int[] arr = {44,33,55,11,22}; //定義功能 //方式一:用String做拼接的方式 String result1 = arrayToString1(arr); System.out.println("result1:"+result1); //result1:[44,33,55,11,22] //方式二:用StringBuffer做拼接的方式 String result2 = arrayToString2(arr); System.out.println("result2:"+result2); //result2:[44,33,55,11,22] } public static String arrayToString1(int[] arr){ String s = ""; s += "["; for(int x = 0; x < arr.length; x++){ if (x == arr.length - 1){ s += arr[x]; }else{ s += arr[x]; s += ','; } } s += ']'; return s; } public static String arrayToString2(int[] arr){ StringBuffer sb = new StringBuffer(); sb.append("["); for(int x = 0; x < arr.length; x++){ if (x == arr.length-1){ sb.append(arr[x]); }else{ sb.append(arr[x]).append(","); } } sb.append("]"); return sb.toString(); } }
6、練習題:把字符串反轉
public class StringBufferDemo09 { public static void main(String[] args) { String s = "I love Java"; String result1 = myReverse1(s); System.out.println("result1:"+result1); //result1:avaJ evol I String result2 = myReverse2(s); System.out.println("result2:"+result2); //result2:avaJ evol I } public static String myReverse1(String s){ String result = ""; char[] ch = s.toCharArray(); for(int x = s.length()-1; x >= 0; x--){ result += ch[x]; } return result; } public static String myReverse2(String s){ return new StringBuffer(s).reverse().toString(); } }
7、判斷一個字符串是否是對稱的。
public class StringBufferDemo10 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入一個字符串:"); String str = sc.nextLine(); //abcba boolean result1 = isSymmertrical1(str); System.out.println("result1:"+result1); //result1:true boolean result2 = isSymmertrical2(str); //result2:true System.out.println("result2:"+result2); } public static boolean isSymmertrical1(String s){ boolean flag = true; char ch[] = s.toCharArray(); for(int start = 0, end = ch.length-1; start <= end;start++,end--){ if (ch[start] != ch[end]){ flag = false; break; } } return flag; } public static boolean isSymmertrical2(String s){ return new StringBuffer(s).reverse().toString().equals(s); } }
8、了解一下StringBuilder類
一個可變的字符序列。此類提供一個與
StringBuffer
兼容的 API,但不保證同步。該類被設計用作
StringBuffer
的一個簡易替換,用在字符串緩沖區被單個線程使用的時候(這種情況很普遍)。如果可能,建議優先采用該類,因為在大多數實現中,它比
StringBuffer
要快。
只要將StringBuffer的功能替換到StringBuilder就可以了。
9、String,StringBuffer,StringBuilder的區別
1)String是內容不可變的,而StringBuffer,StringBuilder都是內容可變的。
2)StringBuffer是同步的,數據安全,效率低;StringBuilder是不同步的,數據不安全,效率高
10、StringBuffer和數組的區別?
A:二者都可以看出是一個容器,裝其他的數據。
B:但是呢,StringBuffer的數據最終是一個字符串數據。
C:而數組可以放置多種數據,但必須是同一種數據類型的。
11、形式參數問題
A:String作為參數傳遞
B:StringBuffer作為參數傳遞
形式參數:
基本類型:形式參數的改變不影響實際參數
引用類型:形式參數的改變直接影響實際參數
注意:
String作為參數傳遞,效果和基本類型作為參數傳遞是一樣的。
public class StringBufferDemo11 { public static void main(String[] args) { String s1 = "hello"; String s2 = "world"; System.out.println(s1 + "---" + s2);//hello---world change(s1, s2); System.out.println(s1 + "---" + s2);//hello---world StringBuffer sb1 = new StringBuffer("hello"); StringBuffer sb2 = new StringBuffer("world"); System.out.println(sb1 + "---" + sb2);//hello---world change(sb1, sb2); System.out.println(sb1 + "---" + sb2);//hello---worldworld } //Stringz作為形參傳遞不會改變實參 public static void change(String s1, String s2) { s1 = s2; s2 = s1 + s2; } //StringBuffer作為形參,如果直接賦值則不會影響實參,但是如果是使用方法改變形參則會影響實參 public static void change(StringBuffer sb1, StringBuffer sb2) { sb1 = sb2; sb2.append(sb1); } }