Java字符串——StringBuilder概念、常用方法、与String的对比
StringBuilder概述
1. String与StringBuilder的区别及应用场景
String具有不可变性,而StringBuilder不具备。
(1) String创建后是不可以修改的,而StringBuilder是可以修改的,案例:
String str = “abc”;
String str1 = str + “de”;
System.out.println(“str=”+str);
System.out.println(“str1=”+str1);
运行结果:
str = abc
str1 = abcde
从结果可以看出,str+“de”
并没有改变str的值,这就是 字符串的不可变性 ,进行操作时,字符串自身的内容并没有发生变化。
再来看一下StringBuilder的使用,案例:
StringBuilder sb = new StringBuilder(“abc”);
ab.append(“de”);//在字符串abc后连接字符串de
System.out.prinln(sb);
运行结果:
abcde
可以看到StringBuilder对象的值发生了变化,从abc变成了abcde。
(2) String比StringBuilder的执行效率要低,因为在运行时产生一些String对象,这样会耗费一些时间。
(3) 应用场景:如果有少量的字符串操作,可以使用String,否则使用StringBuilder。
2. StringBuilder和StringBuffer
二者基本相似。
StringBuffer是线程安全的,StringBuilder则没有,所以性能略高。
StringBuilder的常用方法
1. 案例:StringBuilder
public class StringBuilderDemo1 {
public static void main(String[] args) {
// 定义一个字符串"你好"
StringBuilder str=new StringBuilder("你好");
//在"你好"后面添加内容,将字符串变成"你好,study!"
str.append(',');
str.append("study!");
System.out.println("str="+str);
System.out.println("str="+str.append(',').append("study!"));
}
}
运行结果:
str=你好,study!
str=你好,study!,study!
2. 案例:两种方式变换字符串
public class StringBuilderDemo1 {
public static void main(String[] args) {
// 定义一个字符串"你好"
StringBuilder str=new StringBuilder("你好");
System.out.println("str="+str.append(',').append("study!"));
//将字符串变成"你好,study!"
//两种方式:
//1、使用delete方法删除study,然后再插入study
System.out.println("替换后:"+str.delete(3, 8).insert(3, "study"));
//2、使用replace方法直接替换
System.out.println("替换后:"+str.replace(4, 8, "study"));
//在字符串"你好,study"中取出"你好"并输出
System.out.println(str.substring(0,2));
}
}
运行结果:
str=你好,study!
替换后:你好,study!
替换后:你好,study!
你好