在Java中拆分字符串与空元素 [英] Splitting String in Java with empty elements
问题描述
我正在逐行读取.csv文件。一行可以看例如下: String str =10,1 ,,,,
。
I'm reading from a .csv File line by line. One line could look for example as following: String str = "10,1,,,,"
.
现在我想根据,拆分: String [] splitted = str.split(,);
现在的问题是这只会产生2个元素但我希望有5个元素,前两个元素应该包含10个和1个,另外3个应该只是一个空字符串。
Now I would like to split according to ",": String[] splitted = str.split(",");
The problem now is that this only results in 2 elements but I would like to have 5 elements, the first two elements should contain 10 and 1 and the other 3 should be just an empty String.
另一个例子是 String str =0 ,,,,,
只产生一个元素,但我希望有5个元素。
Another example is String str = "0,,,,,"
which results in only one element but I would like to have 5 elements.
最后一个例子是 String str =9 ,,, 1,
,它给出了2个元素(9和1),但我希望有5个元素。第一个元素应该是9,第四个元素应该是1,所有其他元素应该是一个空字符串。
The last example is String str = "9,,,1,,"
which gives 2 elements (9 and 1), but I would like to have 5 elements. The first element should be 9 and the fourth element should be 1 and all other should be an empty String.
如何做到这一点?
推荐答案
您需要将它与 -1
参数一起使用
You need to use it with -1
parameter
String[] splitted = str.split(",", -1);
之前已经讨论过,例如:
Java:String split():我希望它在末尾包含空字符串
This has been discussed before, e.g. Java: String split(): I want it to include the empty strings at the end
但是 split
真的不应该解析csv的方式,当你有一个包含逗号的字符串值时,你可能会遇到问题
But split
really shouldn't be the way you parse a csv, you could run into problems when you have a String value containing a comma
23,"test,test","123.88"
split
会将该行拆分为4个部分:
split
would split the row into 4 parts:
[23, "test, test", "123.88"]
我不认为你想要那样。
这篇关于在Java中拆分字符串与空元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!