1. 借助JDK文档, 选取String与StringBuffer 、StringBuilder的常用API,并编写实例测试API的功能。
1.String的charAt
public class zhu {
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#
char charAt(int index)
1).返回值是char类型,参数是int。
2).作用和C语言中字符串的下标取值一样,得到的是串中下标为index的字符。
3).下标从0开始,到w.length()-1 , 同C语言中字符串。An index ranges from 0 to length() - 1.
2.String
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
返回一个String类型的。
使用默认区域设置的规则将此字符串中的所有字符转换为小写。
public class zhu {
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!
}
}
Hello,Nice to Meet You!
Hello,Nice to Meet You!
hello,nice to meet you!
3.StringBuffer的append(char[] str)
StringBuffer
append(char[] str)
Appends the string representation of the char array argument to this sequence.
返回一个StringBuffer 类型。
将括号里的字符串加到原字符串后面
public class zhu {
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$
2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
相同点:
1、内部实现基于字符数组,封装了对字符串处理的各种操作
2、可自动检测数组越界等运行时异常
不同点:
1、String内部实现基于常量字符数组,内容不可变;
StringBuffer、StringBuilder基于普通字符数组,数组大小可根据字符串的实际长度自动扩容,内容可变
2、性能方面,对于字符串的处理,相对来说
StringBuilder >StringBuffer>String
3、StringBuffer线程安全;StringBuilder非线程安全
使用场景:
String:对安全要求更高。
StringBuffer、StringBuilder:对性能要求更高
3. 为什么不建议在for循环中使用“+”进行字符串拼接?
字符串常量在拼接过程中,是将String转成了StringBuilder后,使用其append方法进行处理的。
那么也就是说,Java中的+
对字符串的拼接,其实现原理是使用StringBuilder.append
。
在并发场景中进行字符串拼接的话,要使用StringBuffer
来代替StringBuilder
。