1.创建StringBuffer对象:
-
StringBuffer类是可变字符串类
-
capacity( ):输出字符串的容量大小
-
new StringBuffer():
//定义一个空的字符串缓冲区,默认含有16个字符的容量 StringBuffer str=new StringBuffer(); System.out.println(str.capacity()); //输出:16 -
new StringBuffer(int length):
//定义一个含有10个字符容量的字符串缓冲区 StringBuffer str=new StringBuffer(10); System.out.println(str.capacity()); //输出:10 -
new StringBuffer(String str):
//定义一个含有(16+4)字符容量的字符串缓冲区,"青春无悔"为4个字符 StringBuffer str=new StringBuffer("青春无悔"); System.out.println(str.capacity()); //输出:20
2.追加字符串:
-
append(String s):
StringBuffer str=new StringBuffer("青春无悔"); str.append("吴阿斯顿")
3.替换字符:
-
setCharAt(int index,char ch):
StringBuffer str=new StringBuffer("helloWorld"); str.setCharAt(4,'p'); //输出:hellpWorld
4.反转字符串:
-
reverse():
StringBuffer str=new StringBuffer("helloWorld"); str.reverse(); //输出:dlroWolleh
5.删除字符串:
-
deleteCharAt(int index):删除指定位置的字符
StringBuffer str=new StringBuffer("helloWorld"); str.deleteCharAt(4); //输出:hellWorld -
delete(int start,int end):删除指定索引到指定索引的字符,范围:[start,end)
StringBuffer str=new StringBuffer("helloWorld"); str.delete(1,4); //输出:hellWorld