基于指定数组大小的切割字符串(java字符串分割性能比较)

来源:互联网 发布:网络消费者权益保护 编辑:程序博客网 时间:2024/06/06 03:30

参看:http://kfyfly.iteye.com/blog/1105716

/**

* 基于指定数组大小的切割字符串
* @param str
* @param tag
* @param arraySize
* @return
*/
public static String[] split(String str,String tag,int arraySize){
String[] result = new String[arraySize];
int k=0,count=0;  
for (int i = 0; i < str.length(); i++) {
if(str.substring(i,i+1).equals(tag)){
if(count==0){
result[count] = str.substring(0, i);
}else if(count==(arraySize-2)){//如果是倒数第二个元素
result[count] = str.substring(k+1, i);
result[arraySize-1] = str.substring(i+1, str.length());
}else{
result[count] = str.substring(k+1, i);
}
k=i;count++;
}
}
return result;
}
/**
* 基于指定数组大小的切割字符串
* @param str
* @param tag
* @param arraySize
* @return
*/
public static String[] split(String str,char tag,int arraySize){
String[] result = new String[arraySize];
int k=0,count=0;  
for (int i = 0; i < str.length(); i++) {
if(str.charAt(i)==(tag)){
if(count==0){
result[count] = str.substring(0, i);
}else if(count==(arraySize-2)){//如果是倒数第二个元素
result[count] = str.substring(k+1, i);
result[arraySize-1] = str.substring(i+1, str.length());
}else{
result[count] = str.substring(k+1, i);
}
k=i;count++;
}
}
return result;

}


测试:

package com.dlmu.database.manager.test;


import com.dlmu.database.manager.util.Util;


public class TestSplit {


/**
* @param args
*/
public static void main(String[] args) {
String str = "sfsdf aaaaaaa ssssssssss rrrrrrrrr";
String str1 = "sfsdf bbbbbbbbb ccccccccccc eeeeeeeee";
String[] temp = null;
long start = System.currentTimeMillis();
for(int i = 0;i < 1000000;++i){
temp = Util.split(str," ",4);
}
System.out.println("string take time:"+(System.currentTimeMillis()-start));
System.out.println("temp[0]-------"+temp[0]);
System.out.println("temp[1]-------"+temp[1]);
System.out.println("temp[2]-------"+temp[2]);
System.out.println("temp[3]-------"+temp[3]);
String[] temp2 = null;
long start1 = System.currentTimeMillis();
for(int i = 0;i < 1000000;++i){
temp2 = Util.split(str,' ',4);
}
System.out.println("char take time:"+(System.currentTimeMillis()-start1));
System.out.println("temp2[0]-------"+temp2[0]);
System.out.println("temp2[1]-------"+temp2[1]);
System.out.println("temp2[2]-------"+temp2[2]);
System.out.println("temp2[3]-------"+temp2[3]);
String[] temp1 = Util.split(str1," ",4);
System.out.println("temp1[0]-------"+temp1[0]);
System.out.println("temp1[1]-------"+temp1[1]);
System.out.println("temp1[2]-------"+temp1[2]);
System.out.println("temp1[3]-------"+temp1[3]);
}


}


结果:

string take time:2313
temp[0]-------sfsdf
temp[1]-------aaaaaaa
temp[2]-------ssssssssss
temp[3]-------rrrrrrrrr
char take time:594
temp2[0]-------sfsdf
temp2[1]-------aaaaaaa
temp2[2]-------ssssssssss
temp2[3]-------rrrrrrrrr
temp1[0]-------sfsdf
temp1[1]-------bbbbbbbbb
temp1[2]-------ccccccccccc
temp1[3]-------eeeeeeeee

仅供参考