Như vấn đề/yêu cầu của bạn không được tất cả những gì phức tạp một phương pháp tùy chỉnh có thể được sử dụng mà thực hiện hơn 20 lần nhanh hơn và tạo ra kết quả tương tự. Đây là biến số dựa trên kích thước dữ liệu và số hàng được phân tích cú pháp và đối với các vấn đề phức tạp hơn khi sử dụng cụm từ thông dụng là phải.
import java.util.Arrays;
import java.util.ArrayList;
public class SplitTest {
public static void main(String[] args) {
String s = "Sachin,,M,\"Maths,Science,English\",Need to improve in these subjects.";
String[] splitted = null;
//Measure Regular Expression
long startTime = System.nanoTime();
for(int i=0; i<10; i++)
splitted = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
long endTime = System.nanoTime();
System.out.println("Took: " + (endTime-startTime));
System.out.println(Arrays.toString(splitted));
System.out.println("");
ArrayList<String> sw = null;
//Measure Custom Method
startTime = System.nanoTime();
for(int i=0; i<10; i++)
sw = customSplitSpecific(s);
endTime = System.nanoTime();
System.out.println("Took: " + (endTime-startTime));
System.out.println(sw);
}
public static ArrayList<String> customSplitSpecific(String s)
{
ArrayList<String> words = new ArrayList<String>();
boolean notInsideComma = true;
int start =0, end=0;
for(int i=0; i<s.length()-1; i++)
{
if(s.charAt(i)==',' && notInsideComma)
{
words.add(s.substring(start,i));
start = i+1;
}
else if(s.charAt(i)=='"')
notInsideComma=!notInsideComma;
}
words.add(s.substring(start));
return words;
}
}
Trên máy tính của riêng tôi này sản xuất:
Took: 6651100
[Sachin, , M, "Maths,Science,English", Need to improve in these subjects.]
Took: 224179
[Sachin, , M, "Maths,Science,English", Need to improve in these subjects.]
Nguồn
2013-04-09 15:20:44
Tại sao bạn cứ khăng khăng về việc sử dụng String.split? Có những lựa chọn tốt hơn cho ví dụ này? – user949300