StringBuffer类

引入StringBuffer类的原因

我们知道在Java中的String类具有内容的不可改变性 若修改一个字符串的内容,将会产生一个新的对象,而原来的字符串对象如果不引用的话,就会造成内存垃圾。当这样的操作很频繁时就会影响系统的运行效率。为了解决这一问题,Jav提供了StringBuffer来解决字符串的增删减改的问题。

StringBuffer对象的创建

StringBuffer s=new StringBuffer();//创建一个空对象,默认内存为16
StringBuffer s=new StringBuffer("123452");//创建一个内容为123452的对象
StringBuffer s= new StringBuffer(100);//容量为100

StringBuffer类的常用方法

StringBuffer类的常用方法可以分为:对象自身操作、增加、删除、修改、查询、排序。

1.返回所包含字符串长度
int length();
s.length();

2.在尾部追加内容
void append(datatype);
s.append("asda");
s.append(11);

3.在start位置插入数据
insert(int start,datatype)
s.insert(1,"sd");

4.删除字符串
void deleteCharAt(int index);//删除特定位置
void delete(int start,int end);//从start删除到end

5.获取或改变相应位置的字符
char charAt(index);//获取index位置的字符
void setCharAt(int index,char ch);//将index位置字符改为ch

6.replace(int start,int end,String str)//用str替换从start到end的字符串

7.截取字串
String substring(int start,int end)
//获取从statr到end的字符串如果省略end默认到结尾

8.字符串逆序
s.reverse();

9.StringBuffer对象转为String对象
s.toString;

  • 60
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值