StringBuffer
如果一个字符串要被经常改变,则就必须使用StringBuffer类,String类中的可以通过“+”进行字符串的连接,但在StringBuffer中却只能使用append方法进行字符串的连接。
1.字符串连接操作 append()方法
package test2; import java.util.zip.Inflater; import javax.sound.midi.MidiDevice.Info; public class test1 { public static void main(String[] args) { StringBuffer buf = new StringBuffer(); // 声明StringBuffer对象 buf.append("hello"); buf.append("Word").append("!!!"); // buf.append("\n"); buf.append("数字=").append(1).append("\n"); System.out.println(buf); } }
结果:
helloWord!!!数字=1
2.在任意位置处为StringBuffer添加内容
package test2; import java.util.zip.Inflater; import javax.sound.midi.MidiDevice.Info; public class test1 { public static void main(String[] args) { StringBuffer buf = new StringBuffer(); // 声明StringBuffer对象 buf.append("hello"); buf.append("Word").append("!!!"); buf.append("\n"); buf.append("数字=").append(1).append("\n"); buf.insert(0, "wang"); buf.insert(buf.length(), "b"); System.out.println(buf); } }
结果:
wanghelloWord!!!
数字=1
b