八、字符串
1. 借助JDK文档,选取String与StringBuffer 、StringBuilder的常用API,并编写实例测试API的功能。
String类:
Interface CharSequence——charAt(int index):Returns the char value at the specified index.
package test;
public class test1 {
public static void main(String[] args) {
String str="0123456789";
char c=str.charAt(5);
System.out.println(c);
}
}
//5
StringBuffer类:
Interface Appendable—— append(char c):Appends the specified character to this Appendable.
package test;
public class test1 {
public static void main(String[] args) {
StringBuffer strb=new StringBuffer("01234");
strb.append("56789");
System.out.println(strb);
}
}
//0123456789
StringBuilder类:
Interface CharSequence—— length():Returns the length of this character sequence.
package test;
public class test1 {
public static void main(String[] args) {
StringBuilder Strbd=new StringBuilder("0123456789");
System.out.println(Strbd.length());
}
}
//10
2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
共同点:
都是处理字符串的类,具有类似的处理方法;内部属性都有字符数组。
不同点:
String:
对象内储存的字符串为常量(见下图 private final char[] value),一经赋值就不能改变,进行字符串内容的改变操作时返回的结果是一个新的对象。
jdk中部分属性定义:
应用场景:用在一些字符串内容不改变的场景,确保程序的数据安全,如:作为参数传递(网络、数据库,安全性)、多线程程序。
StringBuffer:
对象内储存的是字符串变量(见下图 char[] value),进行字符串内容的改变操作时返回的结果是同一个对象,比String高效(不需多次创建新的对象);线程安全。
jdk中部分属性定义:
应用场景:用于字符串内容经常改变的场景。
StringBuilder:
和StringBuffer相似(都是继承的AbstractStringBuilder)对象内容可以改变,兼容StringBuffer的API,比StringBuffer更高效,但不线程安全。
jdk中部分属性定义:
应用场景:字符串经常改变的场景,但要注意线程安全。
3. 为什么不建议在for循环中使用“+”进行字符串拼接?
因为对于String类,每次用“+”进行字符串都会返回一个新对象,导致程序执行效率低,资源损耗大。推荐只用StringBuffer类和StringBuilder类的append()方法。
String s = “a” + “b” ;
会自动转化为
String s= new StringBuffer().append(“a” ).append(“b” ).toString();
当执行以下语句,每一次循环都要新建一个StringBuffer对象,并执行toString()
int m = 1;
String s = “a”;
for(int i=0; i<10000;i++){
s = s + m ; //效率低下,需新建一万个对象
}
如果转化为以下语句,则只需新建一次StringBuffer对象,并且不需要反复执行toString()
int m = 1;
StringBuffer st = new StringBuffer(“a”); //效率较高,只需新建一个对象
for(int i=0; i<10000;i++){
st.append(m);
}