Java第七次课程作业

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


public class A {
  public static void main(String[] args){
      String w=new String("hello,nice to meet you");
      System.out.println(w);
      int i;
      for(i=0;i<w.length();++i)
       System.out.print(w.charAt(i)+"#");
 
   
  }
}

运行结果:

hello,nice to meet you
h#e#l#l#o#,#n#i#c#e# #t#o# #m#e#e#t# #y#o#u#

String 的 length()
int length()
Returns the length of this string.
返回string的长度
StringBuffer的append(char[] str)


public class A {
  public static void main(String[] args){
      StringBuffer w=new StringBuffer("Hello,Nice to Meet You!");
      System.out.println(w);
      System.out.println("#"+w.append("\n I am happy")+"#");
      System.out.println("$"+w+"$");
 
   
  }
}

运行结果:

Hello,Nice to Meet You!
#Hello,Nice to Meet You!
 I am happy#
$Hello,Nice to Meet You!
 I am happy$

StringBuilder的append(char[] str)

public class A {
  public static void main(String[] args){
      StringBuilder w=new StringBuilder("Hello,Nice to Meet You!");
      System.out.println(w);
      System.out.println("#"+w.append("\n I am happy")+"#");
      System.out.println("$"+w+"$");
  }
}

运行结果:

Hello,Nice to Meet You!
#Hello,Nice to Meet You!
 I am happy#
$Hello,Nice to Meet You!
 I am happy$

2.请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
String类代表字符串。字符串是一个常量,在被创建后无法更改,然后它也是可共享的。
StringBuffer类是一个类似于 String 的字符串缓冲区,但不能修改。虽然在任意时间点上它都包含某种特定的字符序列,但通过某些方法调用可以改变该序列的长度和内容。
StringBulider类是一个个可变的字符序列。此类提供一个与 StringBuffer 兼容的 API,但不保证同步。该类被设计用作 StringBuffer 的一个简易替换,用在字符串缓冲区被单个线程使用的时候。如果可能,建议优先采用该类,因为在大多数实现中,它比 StringBuffer 要快。
3.为什么不建议在for循环中使用“+”进行字符串拼接?
因为字符串拼接过程中会创建新的对象,所以如果要在一个循环体中进行字符串拼接,就要考虑内存问题和效率问题。而对比之下发现使用StringBulider的效率是最高的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值