String增强类
StringBuffer和StringBuilder类
1.与String相比,效率高而且节省内存
StringBuffer和StringBuilder类:
package com.tiedandan.java常用类.String增强类;
public class Application {
public static void main(String[] args) {
//StringBuffer类,jDK1.0开始,StringBuild类,从5.0开始,效率更高,不太安全。
StringBuilder sb1 = new StringBuilder();//StringBuffer sb1 = new StringBuffer();两个类用法一样
//追加方法append();在字符串后面追加。
System.out.println(sb1.append("java世界第一"));
System.out.println(sb1.append("php也很厉害"));
System.out.println(sb1);
//insert添加方法,可以选择添加的字符串位置
System.out.println(sb1.insert(0,"我的"));
System.out.println(sb1.insert(6,"语言"));
//replace()替换指定位置字符串,
System.out.println(sb1.replace(0,2,"你的"));//含头不含尾
//delete删除指定位置字符串
System.out.println(sb1.delete(0,2));//删除字符串位置同样含头不含尾
//清空字符串
System.out.println(sb1.delete(0,sb1.length()));
}
}
测试String类,StringBuild类,StringBuffer类的运行效率:
package com.tiedandan.java常用类.String增强类;
public class Test {
public static void main(String[] args) {
String str1="";
long start =System.currentTimeMillis();
for (int i = 0; i <99999 ; i++) {
str1+=i;
}
long end = System.currentTimeMillis();
System.out.println("string类累加用时:"+(end-start));
System.out.println("----------------------------");
StringBuilder str = new StringBuilder();
long start2 =System.currentTimeMillis();
for (int i = 0; i <99999 ; i++) {
str.append(i);
}
long end2 = System.currentTimeMillis();
System.out.println("StringBuilder类累加用时:"+(end2-start2));
System.out.println("--------------------------");
StringBuffer str3 =new StringBuffer();
long start3 =System.currentTimeMillis();
for (int i = 0; i <99999 ; i++) {
str3.append(i);
}
long end3 = System.currentTimeMillis();
System.out.println("stringBuffer类累加用时:"+(end3-start3));
}
}