String: 字符串常量
StringBuffer: 字符串變量(線程安全)
StringBuilder: 字符串變量(線程不安全)
執行效率: 大部分情況下 Stringbuilder>StringBuffer>String
StringBuffer類的增刪改查:
1、查找方法:
public static void main(String[] args) { StringBuffer sb=new StringBuffer("this is StringBuffer"); //查找子字符串首次出現的下標,不存在返回-1 System.out.println(sb.indexOf("Str")); System.out.println(sb.indexOf("str")); //指定開始下標,返回首次出現下標,不存在返回-1; System.out.println(sb.indexOf("Str",3)); System.out.println(sb.indexOf("Str",9)); //查找子字符串最后出現的下標,不存在返回-1; System.out.println(sb.lastIndexOf("is")); //指定子字符串結束下標,不存在返回-1; System.out.println(sb.lastIndexOf("is",4));
//查找指定下標的字符
System.out.println(sb.charAt(1)); }
2、增:
1 public static void main(String[] args) { 2 StringBuffer sb=new StringBuffer("this is StringBuffer"); 3 //在字符串尾部追加字符串 4 System.out.println(sb.append("\t wey")); 5 //在指定位置插入字符串 6 System.out.println(sb.insert(4, "wey")); 7 }
3、改:
public static void main(String[] args) { StringBuffer sb = new StringBuffer("this is StringBuffer"); // 指定開始,結束下標區間字符替換成指定字符串; System.out.println(sb.replace(0, 4, "who")); // 替換指定下標的字符 sb.setCharAt(2, 'a'); System.out.println(sb); }
4、刪:
public static void main(String[] args) { StringBuffer sb = new StringBuffer("this is StringBuffer");
// 刪除指定開始、結束下標區間的字符
System.out.println(sb.delete(0, 4));
// 刪除指定下標的字符
System.out.println(sb.deleteCharAt(1));
// 清空StringBuffer
sb.delete(0,sb.length());
}
5、截取字符串:
public static void main(String[] args) { StringBuffer sb = new StringBuffer("this is StringBuffer"); // 截取指定區間的字符串 System.out.println(sb.substring(0, 4)); // 開始下標截取字符串,結束下標默認字符串結尾 System.out.println(sb.substring(2)); }
6、字符串反轉:
public static void main(String[] args) { StringBuffer sb = new StringBuffer("this is StringBuffer"); // 字符串倒序 System.out.println(sb.reverse()); }
7、類型轉換:
public static void main(String[] args) { StringBuffer sb = new StringBuffer("this is StringBuffer "); //StringBuffer轉String String str=sb.toString(); //String轉StringBuilder StringBuilder builder=new StringBuilder(str); }