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对象,效率十分低下,而且会浪费更多的空间。