StringBuffer类

String类的字符串内容不可以修改,StringBuffer则是可以改变的。但是字符串的内容不改变
改变的只是内存地址的指向 ,如果现在要想让字符串的内容可以修改,必须使用StringBuffer类。
String使用“+”进行字符的连接 ,而StringBuffer使用append()进行字符的连接。
StringBuffer不能像String那样进行赋值的操作,而必须使用new开辟对象后才能使用。之后在使用append() 方法 ;
例子:
package org.lxh.stringbufferdemo;
public class StringBufferDemo01 {
public static void main(String[] args) {
StringBuffer buf  = new StringBuffer();
buf.append("Hello") ;
buf.append(" ").append("World").append("!!!");
System.out.println(buf) ;
}
}
在程序中只是将“+”替换成了append() 而已,Sting和StringBuffer没有什么直接的关系。
如果希望将StringBuffer类型的数据变为Stirng就要用到toString()方法。
例子:
package org.lxh.stringbufferdemo;
public class StringBufferDemo01 {
public static void main(String[] args) {
StringBuffer buf  = new StringBuffer();
buf.append("Hello") ;
buf.append(" ").append("World").append("!!!");
String str = buf.toString();
System.out.println(str.indexOf("Hello")) ;
}
}
此时就将StringBuffer变为String 这在使用中是一个重点。
一般StringBuffer都用在字符串修改比较频繁的时候。
例子:
package org.lxh.stringbufferdemo;
public class StringBufferDemo01 {
public static void main(String[] args) {
StringBuffer buf  = new StringBuffer();
fun(buf) ;
for(int i=0;i<1000;i++){
buf.append(i);
}
System.out.println(buf);
}
public static void fun(StringBuffer b){
b.append("hello").append("\n") ;

}
}
StringBuffer常用方法:
StringBuffer类中提供了大量的方法,有些方法是与String类中的方法相似的。但也有一些新的方法:
例子:如insert()在指定位置插入
package org.lxh.stringbufferdemo;


public class StringBufferAPIDemo01 {
public static void main(String[] args) {
StringBuffer buf  = new StringBuffer();
buf.append("hello") ;
buf.append(" ").append("world").append("!!!") ;
buf.insert(1, "LXH") ;
buf.insert(0, "MLDN") ;
System.out.println(buf);
}
}运行结果:MLDNhLXHello world!!!
例如delete(int start,int end)删除指定范围的内容
package org.lxh.stringbufferdemo;
public class StringBufferAPIDemo01 {
public static void main(String[] args) {
StringBuffer buf  = new StringBuffer();
buf.append("hello") ;
buf.append(" ").append("world").append("!!!") ;
buf.insert(1, "LXH") ;
buf.insert(0, "MLDN") ;
buf.delete(0, 9) ;
System.out.println(buf);
}
}运行结果:llo world!!!
例如:replace();
例如:reverse()//将字符串内容反转
package org.lxh.stringbufferdemo;
public class StringBufferAPIDemo01 {
public static void main(String[] args) {
StringBuffer buf  = new StringBuffer();
buf.append("hello") ;
buf.append(" ").append("world").append("!!!") ;
buf.insert(1, "LXH") ;
buf.insert(0, "MLDN") ;
//buf.delete(0, 9) ;
buf.reverse(); //字符串反转
System.out.println(buf) ;
}
}
运行结果如下:!!!dlrow olleHXLhNDLM
subString()  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值