当对字符串进行修改的时候,需要使用 StringBuffer 和 StringBuilder 类。
和 String 类不同的是,StringBuffer 和 StringBuilder 类的对象能够被多次的修改,并且不产生新的未使用对象。
StringBuilder 类在 Java 5 中被提出,它和 StringBuffer 之间的最大不同在于 StringBuilder 的方法不是线程安全的(不能同步访问)。
StringBuilder 相较于 StringBuffer 有速度优势。
下面用代码展示StringBuilder 常用的方法和属性(StringBuffer 用法一样)
public class StringBufferTest {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("hello");
sb.append("everyone");//将指定的字符串追加到此字符序列。
System.out.println(sb);
sb.reverse();//将此字符序列用其反转形式取代
System.out.println(sb);
sb.reverse();//再次反转
System.out.println(sb);
sb.delete(0, 5);//移除此序列的子字符串中的字符。
System.out.println(sb);
sb.insert(0, "hello");//将 int 参数的字符串表示形式插入此序列中。
System.out.println(sb);
sb.replace(0, 5, "hi");//使用给定 String 中的字符替换此序列的子字符串中的字符。
System.out.println(sb);
int cap = sb.capacity();//返回StringBuffer的容量为字符串长度的2倍
System.out.println(cap);
char atCahr = sb.charAt(0);//返回此序列中指定索引处的 char 值
System.out.println(atCahr);
char[] chars = new char[]{'a', 'b', 'c'};
sb.getChars(0,2, chars,1);//将字符从此序列复制到目标字符数组 dst。
System.out.println(String.valueOf(chars));
int setIndex = sb.indexOf("on");//返回第一次出现的指定子字符串在该字符串中的索引;不存在则返回-1
System.out.println(setIndex);
int setIndexStart = sb.indexOf("e", 5);//从指定的索引处开始,返回第一次出现的指定子字符串在该字符串中的索引
System.out.println(setIndexStart);
sb.setCharAt(3, 'a');//将给定索引处的字符设置为 ch。
System.out.println(sb);
String substr1 = sb.substring(3);//返回一个新的 String,它包含此字符序列当前所包含的字符子序列
System.out.println(substr1);
String substr2 = sb.substring(3, 5);//返回一个新的 String,它包含此序列当前所包含的字符子序列。
System.out.println(substr2);
String newStr = sb.toString();//返回此序列中数据的字符串表示形式。
System.out.println(newStr);
}
}
加上String,这三个类之间的区别主要是在两个方面,即运行速度和线程安全这两方面。
运行速度快慢为:StringBuilder > StringBuffer > String(String为字符串常量,而StringBuilder和StringBuffer均为字符串变量)
String:适用于少量的字符串操作的情况
StringBuilder:适用于单线程下在字符缓冲区进行大量操作的情况
StringBuffer:适用多线程下在字符缓冲区进行大量操作的情况