写一个java程序比较string和stringbuffer的效率。

如题所述

第1个回答  2011-12-23
public class Test {
public static String detab1(String s){
if(s.indexOf('\t') == -1){
return s;
}
String res = " ";
int len = s.length();
int pos = 0;
int i = 0;
for(;i<len&&s.charAt(i) == '\t';i++){
res+=" ";
pos +=8;
}
for(; i< len;i++){
char c = s.charAt(i);
if(c == '\t'){
do{
res +=" ";
pos++;
}while(pos % 8 !=0);
}else{
res +=c;
pos++;
}
}
return res;
}
public static String detab2(String s){
if(s.indexOf('\t') == -1){
return s;
}
StringBuffer sb = new StringBuffer();
int len = s.length();
int pos = 0;
int i = 0;
for(;i<len&&s.charAt(i) == '\t';i++){
sb.append(" ");
pos +=8;
}
for(;i<len;i++){
char c = s.charAt(i);
if(c =='\t'){
do{
sb.append(' ');
pos++;
}while(pos % 8 != 0);
}else{
sb.append(c);
pos++;
}
}
return s;
}
public static String testlist[] = {"","\t","\t\t\tabc","abc\tdef","1234567\t8","12345678\t9","123456789\t"};
public static void main(String[] args){
for(int i = 0;i<testlist.length;i++){
String tc = testlist[i];
if(!detab1(tc).equals(detab2(tc))){
System.err.println(tc);
}
}
String test_string = "\t\tthis is a test\tof detabbing performance";
int N = 5000;
int i = 0;
long ct = System.currentTimeMillis();
for(i = 1;i<=N;i++){
detab1(test_string);
long elapsed = System.currentTimeMillis()-ct;
System.out.println("String time = " + elapsed);
}
for(i = 1;i<=N;i++){
detab2(test_string);
long elapsed = System.currentTimeMillis()-ct;
System.out.println("StringBuffer time = " + elapsed);
}

}
}本回答被提问者采纳
相似回答
大家正在搜