1、String和StringBuffer的区别:
StringBuffer是线程安全的,但效率特别低的可变字符串。
String是不可改变的字符串,不是线程安全的。
代码:
public class Demo {
public static void main(String[] args) {
//创建可变字符串
StringBuffer sb1 = new StringBuffer();
//可变字符串做追加
StringBuffer sb2 = sb1.append(true);
//判断追加后字符串的地址
System.out.println(sb1 == sb2);//结果为true
String s1 = "abc";
//字符串加上任何类型返回的都是字符串
String s2 = s1 + true;
System.out.println(s1 == s2);//结果为false
}
}
三种构造器:
public class Demo {
public static void main(String[] args) {
//创建可变字符串,默认的容量是16个字符长度
StringBuffer sb = new StringBuffer();
System.out.println("可变字符串的长度: "+sb.length()+" 容量"+sb.capacity());
sb.append("hellohellohellohello");
System.out.println("可变字符串的长度: "+sb.length()+" 容量"+sb.capacity());
//第二种构造方法,指定可变字符串的容量
StringBuffer sb1 = new StringBuffer(10);
System.out.println("可变字符串的长度: "+sb1.length()+" 容量"+sb1.capacity());
sb1.append("hellohellohellohello");
System.out.println("可变字符串的长度: "+sb1.length()+" 容量"+sb1.capacity());
//创建一个带有字符串参数的可变字符串
StringBuffer sb2 = new StringBuffer("hellohellohellohello");
System.out.println("可变字符串的长度: "+sb2.length()+" 容量"+sb2.capacity());
}
}
append方法:
public class Demo {
public static void main(String[] args) {
//创建可变字符串,默认的容量是16个字符长度
StringBuffer sb = new StringBuffer();
//可以拼接许多类型
sb.append(true)
.append('a')
.append(new char[] {'l','j','c'})
.append("hello")
.append(100d)
.append(14.5f)
.append(66);//也可以追加一个对象
System.out.println(sb);//结果truealjchello100.014.566
//可变字符串追加一个可变字符串
StringBuffer sb1 = new StringBuffer("hello world");
sb.append(sb1);
System.out.println(sb);//结果truealjchello100.014.566hello world
}
}
insert方法:
public class Demo {
public static void main(String[] args) {
//创建可变字符串,默认的容量是16个字符长度
StringBuffer sb = new StringBuffer("hello world");
//指定索引位置插入字符串,注意不要越界
sb.insert(2,true);
System.out.println(sb);
//插入字符数组中的元素
sb.insert(2,new char[] {'w','q'});
System.out.println(sb);
//插入字符数组中指定区间的字符
char[] cs = {'a','b','c'};
//第一个参数是要插入的索引位置,第二个参数是要要插入的字符数组
//第三个参数是数组的索引位置,第四个参数是要插入的字符个数
sb.insert(2,cs,0,3);
System.out.println(sb);
}
}
delete方法:
public class Demo {
public static void main(String[] args) {
//创建可变字符串,默认的容量是16个字符长度
StringBuffer sb = new StringBuffer("hello world");
//包含开始索引,但不包含结束索引
sb.delete(2,4);//结果heo world
System.out.println(sb);
//删除指定位置的字符
sb.deleteCharAt(0);
System.out.println(sb);
}
}
替换和反转方法:
public class Demo {
public static void main(String[] args) {
//创建可变字符串,默认的容量是16个字符长度
StringBuffer sb = new StringBuffer("hello world");
//第一个参数是开始替换的索引位置,第二个参数是结束替换的索引位置,第三个参数是要替换的字符串
sb.replace(2,4,"xx");
System.out.println(sb);
//可变字符串的反转
sb.reverse();
System.out.println(sb);
}
}