第八章Java作业

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

public class CharAt {
  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+2)
       System.out.print(w.charAt(i)+" ");
  }
}//charAt  得到字符串中指定位置的字符
public class ToLowerCases {
  public static void main(String[] args){
      String w=new String("Hello,Nice to Meet You!");
      System.out.println(w);//Hello,Nice to Meet You!
      String s=w.toLowerCase();
      System.out.println(w);//Hello,Nice to Meet You!
      System.out.println(s);//hello,nice to meet you!
  }
}//toLowerCase  将字符串中的大写全部转换成小写
public class Lengths {
  public static void main(String[] args){
      String w=new String("hello,nice to meet you");
      System.out.println(w.length());
      w=w+"!";
      System.out.println(w.length());
  }
}//String  求字符串长度

StringBuffer

public class Appends {
  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+"$");
  }
}//append 将括号中字符串加到原字符串后
public class DeleteCharAts{
  public static void main(String[] args){
      StringBuffer w=new StringBuffer("Hello,Nice to Meet You!");
      System.out.println(w);
      System.out.println(w.deleteCharAt(4));
      System.out.println(w);
  }
}//deleteCharAt  删除指定字符

StringBuilder

public class Deletes {
  public static void main(String[] args){
      StringBuilder w=new StringBuilder("Hello,Nice to Meet You!");
      System.out.println(w);
      System.out.println(w.delete(3,7));
      System.out.println(w);
  }
}//delete  删除从起始到结束的所有字符
public class Appends {
  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);
  }
}//append 将括号中字符串加到原字符串后

2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
共同点:三者均在内部实现了字符数组,封装了对字符串的各种操作,可以自动检测字符串运行时的异常。
不同点:
String基于常量字符数组实现,不能被修改;StringBuffer,StringBuilder基于普通字符数组,可以被修改。在字符串处理方面,三者的性能大小为:StringBuilder > StringBuffer > String。StringBuffer线程安全,StringBuilder非线程安全。
3. 为什么不建议在for循环中使用“+”进行字符串拼接?
循环体内每次需要产生StringBuilder对象,效率十分低下,而且会浪费更多的空间。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值