Java字符串相关类
String类
- String类是一个不可变对象,加减操作性能较差
常用方法
方法 | 作用 |
---|---|
charAt() | 返回指定索引的字符 |
concat() | 返回两个字符串的拼接结果 |
concat() | 判断该字符串是否包含指定字符串 |
endsWith() | 判断该字符串是否以指定字符串结尾 |
startsWith() | 判断该字符串是否以指定字符串开头 |
replaceAll() | replaceAll()与replace()都是替换全部指定字符串,不同的是replaceAll()方法可以使用正则表达式 |
StringBuffer类与StringBuilder类
- StringBuffer与StringBuilder都是可变字符串
- StringBuffer字符串加减性能比String好,且同步
- StringBuilder字符串加减性能比StringBuffer好,不同步
常用方法
- append / insert / delete / replace / subtring
- length 字符串实际大小,capacity字符串占用空间大小
- trimToSize():去除空隙,将字符串存储压缩到实际大小
StringBuffer存储空间分配
public static void main(String[] args) {
StringBuffer sb1 = new StringBuffer();
System.out.println("sb1 length: " + sb1.length());
System.out.println("sb1 capacity: " + sb1.capacity());
System.out.println("***************************************");
StringBuffer sb2 = new StringBuffer("123");
System.out.println("sb2 length: " + sb2.length());
System.out.println("sb2 capacity: " + sb2.capacity());
sb2.append("456");
System.out.println("sb2 length: " + sb2.length());
System.out.println("sb2 capacity: " + sb2.capacity());
System.out.println("***************************************");
sb2.append("78901234567890");
// 当length大于capacity的时候会在前一个的基础上+1*2
System.out.println("sb2 length: " + sb2.length());
System.out.println("sb2 capacity: " + sb2.capacity());
System.out.println("***************************************");
// 去除空隙,将字符串存储压缩到实际大小
sb2.trimToSize();
System.out.println("sb2 length: " + sb2.length());
System.out.println("sb2 capacity: " + sb2.capacity());
System.out.println("***************************************");
}
运行结果:
sb1 length: 0
sb1 capacity: 16***************************************
sb2 length: 3
sb2 capacity: 19
sb2 length: 6
sb2 capacity: 19***************************************
sb2 length: 20
sb2 capacity: 40***************************************
sb2 length: 20
sb2 capacity: 20***************************************