📄 stringbufferdemo.java
字号:
public class StringBufferDemo
{
StringBuffer strBuf1 = new StringBuffer("Hello world!");
//声明、创建并初始化StringBuffer类的对象strBuf1
StringBuffer strBuf2;
//声明StringBuffer类的对象strBuf2
StringBuffer strBuf3 = new StringBuffer(10);
//声明并创建StringBuffer类的对象strBuf3,并设定其长度为10
public StringBufferDemo()
{
strBuf2 = new StringBuffer("This is Java code.");
//创建并初始化StringBuffer类的对象strBuf2
strBuf3 = new StringBuffer("Hello");
//创建并初始化StringBuffer类的对象strBuf3
String output = "strBuf1:"+strBuf1.toString()+"\nlength="+
strBuf1.length()+"\ncapacity="+strBuf1.capacity();
//使用StringBuffer类的方法toString(),将StringBuffer类对象转化为String型字符串
//使用StringBuffer类的方法length(),来获得该可变字符串的长度
//使用StringBuffer类的方法capacity(),来获得该可变字符串的的最大存储容量
System.out.println(output);
strBuf1.setLength(30);
//使用StringBuffer类的方法setLength(),来设置可变字符串的长度
System.out.print("After add strBuf1's length,");
System.out.println("strBuf1's capacity is:"+strBuf1.length());
strBuf1.ensureCapacity(60);
//使用StringBuffer类的方法ensureCapacity(),来设置可变字符串的最大存储容量
System.out.print("Set strBuf1's capacity,");
System.out.println("Now strBuf1's capacity is:"+strBuf1.capacity());
System.out.println();
System.out.println("strBuf2:"+strBuf2.toString());
System.out.println("Char at 0 in strBuf2 is:"+strBuf2.charAt(0));
System.out.println("Char at 9 in strBuf2 is:"+strBuf2.charAt(9));
char ch[] = new char[strBuf2.length()];
strBuf2.getChars(8,12,ch,0);
//使用StringBuffer类的方法getChars(),来获取strBuf2中第8~12位的字符
System.out.println("The char from 8 to 12 is:");
for(int i=0;i<4;i++)
{
System.out.print("\""+ch[i]+"\",");
}
System.out.println("\n");
System.out.println("strBuf3:"+strBuf3.toString());
System.out.print("After append string to strBuf3,");
strBuf3.append(" world.StringBufferDemo!");
//使用StringBuffer类的方法append(),在strBuf3末尾插入字符串
System.out.println("New strBuf3:\n"+strBuf3.toString());
System.out.print("After set the 5th char,");
strBuf3.setCharAt(11,'!');
//使用StringBuffer类的方法setCharAt(),来更改strBuf3中第11位的字符
System.out.println("the new strBuf3:\n"+strBuf3.toString());
}
public static void main(String[] args)
{
StringBufferDemo stringBufferDemo = new StringBufferDemo();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -