Java学习(81)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!
你好
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值