Java第八章(字符串)课后小结

1.借助JDK文档, 选取String与StringBuffer 、StringBuilder的常用API(函数),并编写实例测试API的功能。

参考:JDK文档
String类中:
1.在这里插入图片描述
作用:得到串中下标为index的字符


public class A{
  public static void main(String[] args){
      String w=new String("welcome");
      System.out.println(w);
      int i;
      for(i=0;i<w.length();++i)
       System.out.print(w.charAt(i)+"#");
  }
}
//运行结果
welcom
w#e#l#c#o#m#

2.在这里插入图片描述
作用:返回string的长度

public class A{
  public static void main(String[] args){
      String w=new String("welcome");
      System.out.print(w.length());
  }
}
//运行结果
7

StringBuffer类中:
1.在这里插入图片描述
作用:将括号里的字符串加到原字符串后面

public class A {
  public static void main(String[] args){
      StringBuffer w=new StringBuffer("welcome");
      System.out.println(w);
      System.out.println("#"+w.append(" you")+"#");
  }
}
//运行结果
welcome
#welcome you#

2.在这里插入图片描述
作用:删除此序列中指定位置的字符

public class A {
  public static void main(String[] args){
      StringBuffer w=new StringBuffer("welcome");
      System.out.println(w);
      System.out.println("#"+w.deleteCharAt(3)+"#");
  }
}
//运行结果
welcome
#welome#

StringBuilder类中:
1.在这里插入图片描述
作用:将括号里的字符串加到原字符串后面

public class A {
  public static void main(String[] args){
      StringBuffer w=new StringBuilder("welcome");
      System.out.println(w);
      System.out.println("#"+w.append(" you")+"#");
  }
}
//运行结果
welcome
#welcome you#

2.在这里插入图片描述
作用:删除原字符串中下标为start(包含)到下标为end(不包含)的子串

public class A {
  public static void main(String[] args){
      StringBuilder w=new StringBuilder("welcome");
      System.out.println(w);
      System.out.println("#"+w.delete(1,4)+"#");
      //0 1 2 3 4 5 6
      //w e l c o m e
      //  * * *
      //删除了下标为1,2,3的字符
  }
}
//运行结果
welcom
#wome#

2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?

共同点:
1.内部实现基于字符数组,封装了对字符串处理的各种操作
2.可自动检测数组越界等运行时异常

不同点:
1.String内部实现基于常量字符数组,内容不可变;
StringBuffer、StringBuilder基于普通字符数组,数组大小可根据字符串的实际长度自动扩容,内容可变
2.性能方面,对于字符串的处理,相对来说 StringBuilder > StringBuffer > String
3.StringBuffer线程安全;StringBuilder非线程安全

应用场景:
String类:
在字符串不经常变化的场景中可以使用String类,例如常量的声明、少量的变量运算。
StringBuffer类:
在频繁进行字符串运算(如拼接、替换、删除等),并且运行在多线程环境中,则可以考虑使用StringBuffer,例如XML解析、HTTP参数解析和封装。
StringBuilder类:
在频繁进行字符串运算(如拼接、替换、和删除等),并且运行在单线程的环境中,则可以考虑使用StringBuilder,例如SQL语句的拼装、JSON封装等。

3.为什么不建议在for循环中使用“+”进行字符串拼接?

我们可以利用反编译后的代码来看到编译的详细过程,
在反编译后的代码中,for循环中的“+”操作,是每次都new了一个StringBuilder,然后再把String转成StringBuilder,再进行append。

而频繁的新建对象当然要耗费很多时间了,不仅仅会耗费时间,频繁的创建对象,还会造成内存资源的浪费,大大降低了效率。

所以,在循环体内,字符串的连接方式,一般建议使用 StringBuilder 的 append 方法进行扩展。而不是使用“+”进行拼接。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值