StringBuffer类的操作方法
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); }