StringAPI方法是对char数组的操作算法
没有API,或者不用API可以利用for循环处理字符数组实现相应功能,如果优化的话,性能好于API
String对象创建后有不变性
String对象一有变化就要赋予新的字符串数组,原对象不变
String name = "xxxx"
name = name.api//name原先引用的对象本身不变,name变量引用新的对象数组
如果这样写
name.api
println(name);//返回name原对象
StringBuilder维护了一个长度可变,内容可变的字符数组
String的连接计算是使用StringBuilder实现的
String s = "xx"
String ss = s + 1 +3;//new StringBuilder()
String s = "a";
s+=a;//new StringBuilder()String的连接计算是使用StringBuilder实现的
s+=a;//new StringBuilder()
s+=a;//new StringBuilder()
s+=a;//new StringBuilder()
s+=a;//new StringBuilder()
System.out.print(s);//aaaaaa
上述代码产生了数个StringBuilder垃圾对象,影响性能。应该这样写
StringBuilder buf = new StringBuilder("a");
buf.append("a");
buf.append("a");
buf.append("a");
buf.append("a");
buf.append("a");
System.out.print(buf.toString());
单行用+就可以
package terenaAPI;
import org.junit.Test;
public class TestString {
//@Test
public void testStringPool(){
String tom = "杯子1";
String jerry = "杯子1";
String andy = "杯子"+1;
int i = 1;
String sandy = "杯子"+i;
System.out.println(tom==jerry);
System.out.println(tom==andy);
System.out.println(tom==sandy);
}
//@Test
public void testTrim(){
String name = " \n\t\r tom\n \r\t";//String对象不变,name变量可以引用新的对象
name = name.trim();//返回结果与原字符串相同返回原字符串,不同则返回新字符串
System.out.println(name);
}
//@Test
public void testTrim2(){
String name = " TOM ";
name.trim();
System.out.println(name);//" TOM "
}
//@Test
public void testCharAt(){
String beauty = "罗霁月";
for(int i=0;i<beauty.length();i++){
System.out.println((int)beauty.charAt(i));//char字符的对应int值
}
}
//@Test
/**
* 字符串相邻的两个字符的操作方法
* !!!!
*/
public void testCharAt2(){
String str = "what is java";
char pre = ' ';
char[] chs = new char[str.length()];
for(int i = 0;i<str.length();i++){
char ch = str.charAt(i);
//System.out.println(pre+","+ch);
if(pre==' '&& (ch>='a'&&ch<='z')){
ch = (char)(ch+('A'-'a'));
}
chs[i] = ch;
pre = ch;
}
String s =new String(chs);
System.out.print(s);
}
//test endsWith() startWith
//@Test
public void testStartWith(){
String file = "tetris.PNG";
if(file.toLowerCase().endsWith(".png")){
System.out.println("image");
}
String cmd = "get xxx";
if(cmd.startsWith("get")){
System.out.println("get cmd");
}
}
//test valueOf
@Test
//test StringBuilder
public void testStringBuilder(){
StringBuilder buf = new StringBuilder("ABC");
buf.append("CDE").delete(3, 4).append("LMN").insert(5, "FGHIJK");
String str = buf.toString();
System.out.println(str);//ABCDEFGHIJKLMN
}
@Test
public void testStringConnect(){
long start = System.nanoTime();
//todo
long end = System.nanoTime();
System.out.println(end-start);
}
@Test
public void testStringBuilderConnect(){
long start = System.nanoTime();
//todo
long end = System.nanoTime();
System.out.println(end-start);
}
}
//String连接计算
String s1 = "123ABC";
String s2 = "123"+"ABC";
String s3 = 123+"ABC";//"123ABC"
String s4 = 1+2+3+"ABC";//"6ABC"
String s5 = "1"+2+3+"ABC";//"123ABC"
String s6 = '1'+2+3+"ABC";//'1'=49 "54ABC"