-
StringBuffer类的介绍
StringBuffer是字符串缓存区,当new的时候是在堆内存创建了一个对象,底层是一个长度为16的
字符数组当调用添加的方法时,不会再重新创建对象,在不断向原缓冲区添加字符
-
查看字符串缓存区容量和长度(字符数)——capacity/length
StringBuffer x1 = new StringBuffer();
(()); //容器中的字符个数,实际值
(()); //容器的初始容量,理论值
-
字符串缓存区——添加(append)
#可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
#StringBuffer类中重写了toString方法,显示的是对象中的属性值
StringBuffer x = new StringBuffer();
("hello ");
("the ");
("world");
(x);
-
字符串缓存区——插入(insert)
StringBuffer x = new StringBuffer("happy");
(2,"ss"); //在指定位置添加元素
(x);
-
字符串缓存区——替换(replace)
StringBuffer x = new StringBuffer("happy");
(3,5,"cc");//替换指定位置字符串(左闭右开)
(x);
-
字符串缓存区——反转(reverse)
StringBuffer x = new StringBuffer("happy");
(()); //反转字符串
-
字符串缓存区——截取(substring)
StringBuffer x = new StringBuffer("happy");
((2,6));//截取字符串
-
字符串缓存区——删除
删除从指定位置开始指定位置结束的内容,并返回删除后的字符缓冲区本身——delete
StringBuffer sb = new StringBuffer("hello");
((1,2));
根据索引删除掉索引位置上对应的字符,返回删除后的字符缓冲区本身—deleteCharAt
StringBuffer sb = new StringBuffer("hello");
((4));
-
字符串缓存区——清空
方法一:(推荐)
StringBuffer x = new StringBuffer("hello");
(());
(());
(0,()); //清空缓存区
(());
(());
方法二:
//方式二:不建议这种方式清空缓存区,原来的会变成垃圾,浪费内存
StringBuffer x1 = new StringBuffer("hello");
x1 = new StringBuffer();
(());
(());
-
StringBuffer和String相互转换
StringBuffer转换成String
通过构造方法
StringBuffer x1 = new StringBuffer("hello");
String x2 = new String(x1);
(x2);
通过toString方法
StringBuffer x1 = new StringBuffer("hello");
String x3 = ();
(x3);
通过截取字符串方法
StringBuffer x1 = new StringBuffer("hello");
String x4 = (0,());
(x4);
String转化成StringBuffer
通过构造方法
StringBuffer s1 = new StringBuffer("help");
(s1);
通过append方法
StringBuffer s2 = new StringBuffer();
("help");
(s2);
-
当做参数传递时,String和StringBuffer区别
#当做参数传递时原则:基本数据类型的值传递,不改变其值;引用数据类型的值传递,改变其值
#String类虽然是引用数据类型,但是他当作参数传递时和基本数据类型是一样的,不改变其值
#StringBuffer作为参数传递,改变其值