【StringBuffer】
String和StingBuffer都可以存储和操作字符串,不同的是,String是常量字符串,不可以更改;而StringBuffer是变量字符串,底层是char[]数组,方便修改和扩充。
1、StringBuffer的创建
//方法一:未指定缓冲区大小,则默认为16
StringBuffer buffer1 = new StringBuffer();//方法二:指定缓冲区大小
StringBuffer buffer2 = new StringBuffer(3);//方法三:缓冲区大小为字符串的长度加16
String s = "abcde";
StringBuffer buffer3 = new StringBuffer(s);
2、 末尾添加字符串
StringBuffer buffer = new StringBuffer("abc");
buffer.append("de");
3、 指定位置插入字符串
StringBuffer buffer = new StringBuffer("ade");
buffer.insert(1,"bc");
4、删除指定位置字符
StringBuffer buffer = new StringBuffer("abcde");
buffer.deleteCharAt(1);
5、替换连续区域字符串
StringBuffer buffer = new StringBuffer("abcde");
buffer.replace(1,3,"12");
6、字符串反转
StringBuffer buffer = new StringBuffer("abcde");
buffer.reverse();
7、截取指定开始位置到末尾的字符串
StringBuffer buffer = new StringBuffer("abcdefghi");
System.out.println(buffer.substring(3));
8、截取指定开始位置到结束位置的字符串
StringBuffer buffer = new StringBuffer("abcdefghi");
System.out.println(buffer.substring(3, 5));
9、返回当前容量
String s = "abdc";
StringBuffer buffer = new StringBuffer(s);//缓冲区容量
System.out.println(buffer.capacity());
//实际字符串长度
System.out.println(buffer.length());
【StringBuffer】
String和StingBuffer都可以存储和操作字符串,不同的是,String是常量字符串,不可以更改;而StringBuffer是变量字符串,底层是char[]数组,方便修改和扩充。
1、StringBuffer的创建
//方法一:未指定缓冲区大小,则默认为16
StringBuffer buffer1 = new StringBuffer();//方法二:指定缓冲区大小
StringBuffer buffer2 = new StringBuffer(3);//方法三:缓冲区大小为字符串的长度加16
String s = "abcde";
StringBuffer buffer3 = new StringBuffer(s);
2、 末尾添加字符串
StringBuffer buffer = new StringBuffer("abc");
buffer.append("de");
3、 指定位置插入字符串
StringBuffer buffer = new StringBuffer("ade");
buffer.insert(1,"bc");
4、删除指定位置字符
StringBuffer buffer = new StringBuffer("abcde");
buffer.deleteCharAt(1);
5、替换连续区域字符串
StringBuffer buffer = new StringBuffer("abcde");
buffer.replace(1,3,"12");
6、字符串反转
StringBuffer buffer = new StringBuffer("abcde");
buffer.reverse();
7、截取指定开始位置到末尾的字符串
StringBuffer buffer = new StringBuffer("abcdefghi");
System.out.println(buffer.substring(3));
8、截取指定开始位置到结束位置的字符串
StringBuffer buffer = new StringBuffer("abcdefghi");
System.out.println(buffer.substring(3, 5));
9、返回当前容量
String s = "abdc";
StringBuffer buffer = new StringBuffer(s);//缓冲区容量
System.out.println(buffer.capacity());
//实际字符串长度
System.out.println(buffer.length());