import org.junit.Test;
/**
* StringBuilder及其API
*StringBuilder封装可变的字符串,对象创建后可以通过调用方法改变其封装的字符序列。
*StringBuilder有如下常用的构造方式
*/
public class csdnDemo {
/**
* StringBuilder append(String str) 追加字符串
* StringBuilder insert(int dstOffset,String s) 插入字符串
* StringBuilser delete(int start,int end) 删除字符串
* StringBuilder replace(int start,int end,String str) 替换字符串
* StringBuilder reverse() 字符串反转
* */
/**测试StringBuilder的append的方法*/
@Test
public void test01(){
StringBuilder buf = new StringBuilder("Programming Language");//构建新的字符串
buf.append("Java").append("cpp").append("php").append("c#").
append("objective-c");//字符串分别拼接
System.out.println(buf);//输出“Programming LanguageJavacppphpc#objective-c”
}
/**测试StringBuilder的insert的方法*/
@Test
public void test02(){
StringBuilder buf = new StringBuilder("jacacppc#objective-c");//构建新的字符串
buf.insert(9, "php");//在第九号位置插入“php”
System.out.println(buf);//输出“jacacppc#phpobjective-c”
}
/**测试StringBuilder的delete的方法*/
@Test
public void test03(){
StringBuilder buf = new StringBuilder("javaoraclecppc#php");//构建新的字符串
buf.delete(4, 4 + 6);//删除字符串中从第四个位置开始到第10个位置结束
System.out.println(buf);//输出“javacppc#php”
}
/**
* StringBuilder是可变字符串,字符串的内容如果需要平凡改变,建议利用StringBuilder
*/
@Test
public void test04(){
String str1 = "i";
StringBuilder str2 = new StringBuilder("i");
long time1 = System.currentTimeMillis();
for(int i = 0; i < 100000; i ++){
str1 += "i";
}//传统String方法
long time2 = System.currentTimeMillis();
for(int i = 0; i < 100000; i ++){
str2.append("i");
}//StringBuilder的append方法
long time3 = System.currentTimeMillis();
System.out.println(time2 - time1);//String方法时间,输出3262
System.out.println(time3 - time2);//StringBuilder方法时间,输出1
}
}