可变字符串
与String类的区别
:
-
比String的效率高
-
比String节省内存
StringBuffer、StringBuilder两个的用法是一样的
append() 追加
package com; public class Test { public static void main(String[] args) { StringBuffer s1 = new StringBuffer(); s1.append("java"); System.out.println(s1); s1.append("真不错"); System.out.println(s1); } }
insert() 添加
package com; public class Test { public static void main(String[] args) { StringBuffer s1 = new StringBuffer(); s1.append("java"); System.out.println(s1); s1.append("真不错"); System.out.println(s1); s1.insert(0,"我在最前面,"); // 前面为下标值 System.out.println(s1); } }
replace() 替换
package com; public class Test { public static void main(String[] args) { StringBuffer s1 = new StringBuffer(); s1.append("java"); System.out.println(s1); s1.append("真不错"); System.out.println(s1); s1.insert(0,"我在最前面,"); System.out.println(s1); s1.replace(0,6,"hi,"); // 前面为开始到结束的下标位置(遵循含头不含尾的原则) System.out.println(s1); } }
delete() 删除
package com; public class Test { public static void main(String[] args) { StringBuffer s1 = new StringBuffer(); s1.append("java"); System.out.println(s1); s1.append("真不错"); System.out.println(s1); s1.insert(0,"我在最前面,"); System.out.println(s1); s1.replace(0,6,"hi,"); System.out.println(s1); s1.delete(0,3); // 同样遵循含头不含尾原则 System.out.println(s1); } }