public class Demo1
{
public static void main(String args[])
{
StringBuffer buf=new StringBuffer("Hello!");//StringBuffer的构造函数StringBuffer(String str)用字符串初始化其对象
buf.append("Chinese").append("no").append(1);//在StringBuffer中用append();来连接各种不同的数据,返回一个StringBuffer对象,故可以连接多个append
System.out.println(buf); //输出对象
}
}
public class Demo2
{
public static void main(String args[])
{
StringBuffer buf=new StringBuffer("hello world,welcome back");
buf.insert(5,"liuli");//insert(int offset,String str)返回一个StringBuffer类对象
System.out.println(buf);
}
}
public class Demo3
{
public static void main(String args[])
{
StringBuffer buf=new StringBuffer("world");
buf.reverse();//反转字符串
String str=buf.reverse().toString();//反转字符串通过字符串输出
System.out.println(str);输出反转后的字符串
}
}
public class Demo4
{
public static void main(String args[])
{
StringBuffer buf=new StringBuffer("hello world");
String str=buf.replace(0,4,"hi").toString();//用特定的串取代指定的子串,用toString输出
System.out.println(str);
}
}
public class Demo5
{
public static void main(String args[])
{
StringBuffer buf=new StringBuffer("hello world");
if(buf.indexOf("ell"))//求取子串第一次出现的位置
{
System.out.println(buf);
}
}
}
Stringbuffer的应用