参考链接: Java stringbuffer和stringbuilder之间的差异
1、相同点:String、StringBuffer、StringBuilder三个类都是用来封装字符串的
2、不同点:
String类是不可变类,即一旦一个String对象被创建后,包含在这个对象中的字符串是不可以改变的StringBuffer对象代表一个字符序列可变的字符串StringBuilder也代表一个可变字符串对象,与StringBuffer相比,StringBuilder是线程不安全的,而StringBuffer是线程安全的
3、方法:
(1)String类中主要的方法:
char charAt(int index):获取字符串中indext位置的字符 String concat(String str):将该String对象与str连接在一起 String substring(int beginIndex):获取从beginIndex位置开始到结束的子字符串 String substring(int beginIndex,int endIndex):获取从beginIndex位置到endIndex位置的字符串 char[] toCharArray():将String对象转换成char数组 String toLowerCase():将字符串全部变为小写 String toUpperCase():将字符串全部变为大写
(2)StringBuffer、StringBuilder中的主要方法:
append():添加字符序列insert():插入字符串replace():替换字符串delete():删除字符reverse():反转字符串seLength():修改字符序列长度capacity():获取StringBuffer、StringBuilder对象的容量
public class ScannerTest {
public static void main(String[] args){
StringBuffer sb=new StringBuffer();
//添加
sb.append("hello");
System.out.println(sb);
//插入
sb.insert(0, "China ");
System.out.println(sb);
//替换
sb.replace(5, 6, ",");
System.out.println(sb);
//删除
sb.delete(5, 6);
System.out.println(sb);
//反转
sb.reverse();
System.out.println(sb);
System.out.println(sb.length());
System.out.println(sb.capacity());
//修改长度,只保留长度之前的数值
sb.setLength(5);
System.out.println(sb);
}
}
/*输出结果:
hello
China hello
China,hello
Chinahello
ollehanihC
10
16
olleh
*/
(3)一旦StringBuffer、StringBuilder生成了最后想要的字符串,就可以调用它的toString()方法将其变为一个String对象
在上述代码后加入这两句,将sb转换为str,这个str无法改变。
String str=sb.toString();
System.out.println(str);
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有