我有一个逗号分隔的文件,其中有许多行类似于下面的行。
Sachin,,M,"Maths,Science,English",Need to improve in these subjects.
引号用于转义用于表示多个值的分隔符逗号。
现在,如果可能的话,如何使用 String.split()
在逗号分隔符上拆分上述值?
原文由 FarSh018 发布,翻译遵循 CC BY-SA 4.0 许可协议
由于您的问题/要求并不那么复杂,因此可以使用执行速度超过 20 倍并产生相同结果的自定义方法。这是基于数据大小和解析行数的变量,对于更复杂的问题,必须使用正则表达式。
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;
}
}
在我自己的电脑上,这会产生:
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.]
原文由 Menelaos 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.2k 阅读
8 回答6k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答3.2k 阅读
2 回答3.9k 阅读
1 回答2.2k 阅读✓ 已解决
输出: