Java中的基礎----StringBuffer的介紹、基本操作
阿新 • • 發佈:2019-01-08
Java提供StringBuffer類實現對字串內容進行的動態修改。
StringBuffer類提供3種構造方法:
1)StringBuffer()
2)StringBuffer(int length)
3)StringBuffer(String s)
基本操作1:新增操作append()
StringBuffer sb=new StringBuffer(); sb.append("me");//string sb.append('a');//char sb.append(true);//boolean sb.append(1);//int System.out.print(sb.toString());
輸出結果:meatrue1
基本操作2:插入操作insert()
StringBuffer sb=new StringBuffer(); sb.insert(0, "wo");//insert(int offset,String s) sb.insert(0, 1);//insert(int offset,int a) sb.insert(0, true);//insert(int offset,Boolean b) sb.insert(0, new char[]{'a','b','c'});//insert(int offset,char[] c) sb.insert(0, new char[]{'a','b','c'},1,2);//insert(int offset,char[] c,int fromindex,int endindex) System.out.print(sb.toString());
輸出結果:bcabctrue1wo
基本操作3:StringBuffer轉為String:toString()
StringBuffer sb=new StringBuffer();
sb.append("wo");
String s=sb.toString();
System.out.print(s);
輸出結果:wo
基本操作4:取字元charAt(int index)
StringBuffer sb=new StringBuffer();
sb.append("wo");
char s=sb.charAt(0);
System.out.print(s);
輸出結果:w
基本操作5:刪除字元delete(int start,int end)、deleteCharAt(int index)
StringBuffer sb=new StringBuffer("I just want to try !");
sb.delete(1,sb.length());
System.out.print(sb.toString());
輸出結果:I
StringBuffer sb=new StringBuffer("I just want to try !");
sb.deleteCharAt(0);
System.out.print(sb.toString());
輸出結果;just want to try!基本操作6:清空字串:SetLength(int newLength)=======(通過重新設定緩衝區長度)
StringBuffer sb=new StringBuffer("I just want to try !");
sb.setLength(0);
System.out.println(sb);
輸出結果:(無)基本操作7:內容替換replace(int start,int end,String str)
StringBuffer sb=new StringBuffer("I just want to try !");
sb.replace(0, sb.length(),new String("I want to be replaced"));
System.out.println(sb.toString());
輸出結果:I want to be replaced
基本操作8:取子字串subString(int start,int end)、subString(int start)
StringBuffer sb=new StringBuffer("I just want to try !");
String s=sb.substring(0,5); //sb.subString(0)
System.out.println(s);
輸出結果:I jus基本操作9:字串反轉reverse()
StringBuffer sb=new StringBuffer("I just want to try !");
sb.reverse();
System.out.println(sb.toString());
輸出結果:! yrt ot tnaw tsuj I
基本操作10:獲取長度length()為字串長度、capacity()為緩衝區長度
StringBuffer sb=new StringBuffer("I just want to try !");
int len1=sb.length();
int len2=sb.capacity();
System.out.println(len1+","+len2);
輸出結果:20,36