StringBuffer类

来源:互联网 发布:mysql数据库指令 编辑:程序博客网 时间:2024/04/29 12:52
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()  
原创粉丝点击