StringBuffer

StringBuffer
StringBuffer 是 线程安全(耗费资源)的可变序列
StringBuilder(1.5之后)是 线程不安全(不好非资源)的可变序列
1添加 append(可以添加多种类型 包括基本数据类型)


***```添加 append***
---------------*public static void fun2(){
  //StringBuffer 长度是可变的
  //对StringBuffer 操作的时候 改变是其本身
  StringBuffer sb1 = new StringBuffer();
  //对象点方法
  sb1.append("long").append("z").append("e");
  System.out.println(sb1);
}
```*

**插入 insert**





"se-preview-section-delimiter">
public static void fun3(){
 StringBuffer sb1 = new StringBuffer();
 //按照下标(偏移量)去插入
 //不要越界
 sb1.insert(0,"yaojinni");
 //把索引位置的字符替换掉
 sb1.setCharAt(6,'f');
 sb1.setCharAt(6,'5');
 System.out.println(sb1);
}
删除 delete

public static void fun4(){
StringBuffer string = new StringBuffer();
string.append(“qujinyao”);
//删头不删尾
string.delete(0,4);
//根据索引删除 索引位置的字符
string.deleteCharAt(2);
System.out.println(string);
}

替换-----replace

public static void fun5(){
StringBuffer string = new StringBuffer();
string.replace(0,4,”u”);
System.out.println(string);
}


反转----reverse

public void fun6(){
StringBuffer string = new StringBuffer();
string.append(“qujinyao”);
string.reverse();
System.out.println(string);
}

public static void fun7(){
 String string = new String();
 string = "qujinyao";
 StringBuffer string2 = new StringBuffer(string);
 string2.reverse();
 String string3 = new String(string2);
 System.out.println(string3);
}

总结那么多,我们下面来做个题目
需求
把int[] array = new int[]{1,2,3,4,5}
输出[1,2,3,4,5]
要求使用String 和 StringBuffer

一 用String

public static void fun8(){
  int[] array = new int[]{1,2,3,4,5};
  String string = "[";
  //取出数组的每一个值
  for(int i =0;i<array.length;i++){
  //判断最后一位元素,不加逗号
  if( i == array.length;i++){
  //判断最后一位元素,不加逗号
  if(i == array.length-1){
   string = string+array[i]+"]";
 }else{
 string = string+array[i]+",";

}
  }
  System.out.println(string);
  }
二 用StringBuffer

public static void fun9(){
int[] array = new int[]{1,2,3,4,5};
StringBuffer sb = new StringBuffer();
sb.append(“[“);
for (int i = 0; i < array.length; i++) {
if (i == array.length - 1) {
sb.append(array[i]).append(“]”);
}else {
sb.append(array[i]).append(“,”);
}
}
System.out.println(sb.toString());

}

}
“`

权限修饰符
1 public 公开的
2 protected 受保护的
3 default 默认的(就是不添加修饰符)
4 private 私有的

你可能感兴趣的:(java,stringbuffer,stringbuilder,线程安全)