//StringBuffer:可变字符序列,一个类似与String的字符缓冲区
/*特点:
* 1.可以对字符串进行修改
* 2.长度是可变的
* */
public class Demo2 {
public static void main(String[] args) {
/*构造:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)*/
StringBuffer sb1 = new StringBuffer();
System.out.println("capacity:"+sb1.capacity());
System.out.println("length:"+sb1.length());
StringBuffer sb2 = new StringBuffer(32);
// System.out.println("capacity:"+sb1.capacity());
// System.out.println("length:"+sb1.length());
StringBuffer sb3 = new StringBuffer("lkk");
// System.out.println("capacity:"+sb3.capacity());
// System.out.println("length:"+sb3.length());
/*添加:
StringBuffer append(data);
StringBuffer insert(index,data);*/
// 1. append();将指定的字符串追加到此字符序列
System.out.println("追加前sb1:"+sb1);
sb1.append("hello");
sb1.append("world");
System.out.println("追加后sb1:"+sb1);
// 2. StringBuffer insert(index,data);在指定索引处,插入指定字符
System.out.println("insert前:"+sb1);
sb1.insert(3,"a");
System.out.println("insert后:"+sb1);
/*删除:
StringBuffer delete(start,end):包含头,不包含尾。
StringBuffer deleteCharAt(int index):删除指定位置的元素 */
//1.delete,依旧是删除[ )区间内的元素,删除起始位置,不删除最终位置
System.out.println("delet前:"+sb1);
sb1.delete(1, 5);
System.out.println("delet后:"+sb1);
//2.tringBuffer deleteCharAt(int index)
System.out.println("delete指定前:"+sb1);
sb1.deleteCharAt(5);
System.out.println("delete指定后:"+sb1);
System.out.println("-------------------------------");
/* 查找:
char charAt(index);
int indexOf(string);*/
//1.char charAt(index);查找并返回指定位置处的字符
System.out.println("sb1:"+sb1);
System.out.println(sb1.charAt(2));
//2.int indexOf(string);查找并返回指定字符的下标
System.out.println(sb1.indexOf("w"));
/*修改:
StringBuffer replace(start,end,string);
void setCharAt(index,char);*/
//1.StringBuffer replace(start,end,string);
//用指定字符串string替代指定开始结束索引处的内容,修改区间也是[ ),左闭右开
System.out.println("修改前sb1:"+sb1);
System.out.println(sb1.replace(0, 2, "hello"));
//2.void setCharAt(index,char)设置指定索引处的字符,原字符会被替换
sb1.setCharAt(4, 'e');
System.out.println(sb1);
}
}