Possible Duplicate:
Java split() method strips empty strings at the end?可能重复:Java split()方法在结尾处删除空字符串?
we have a requirement like reading a file content and uploading the data to the database. the file content will be separated by delimiter '|' like this
我们有一个要求,比如读取文件内容并将数据上传到数据库。文件内容将由分隔符“|”分隔像这样
4000|name|state|city|zip||country|||address||
I can also have null values for certain column for which there is no data in between "|". for example '||' between zip and country. my problem is string.split("//",'|') is taking the in between null values and returning array considering null values as an element. But the trailing '||' after address is not being considered. As used in the example above, when i use string.split("//",'|') i shd get an string array element of array size 11 but i get only 10.the last null is not getting retreived. Can anyone help with the solution?
对于某些列,我也可以使用空值,“|”之间没有数据。例如'||'拉链和国家之间。我的问题是string.split(“//”,“|”)在空值之间取值,并将空值作为元素返回数组。但尾随'||'在地址未被考虑之后。正如上面的例子中所使用的,当我使用string.split(“//”,“|”)时,我得到一个数组大小为11的字符串数组元素,但我只得到10.最后一个null没有被检索。有人可以帮忙解决这个问题吗?
2 个解决方案
#1
4
Just use the regular split(String, int)
method inside the String
class:
只需在String类中使用常规split(String,int)方法:
String line = "4000|name|state|city|zip||country|||address||";
String data[] = line.split("\\|", -1); // escaped, because of regular expressions
The minus one is a convention that indicates that the string will be split as you want it.
减号是一种约定,表示字符串将根据需要进行拆分。
#2
0
Yes to use split is obvious, but you may consider this options too:
是的,使用拆分是显而易见的,但你也可以考虑这个选项:
Why not just using string.indexOf("|", indexToStartFrom) ? Is a bit of hassle, but works for sure without having to think too much about regex.
为什么不使用string.indexOf(“|”,indexToStartFrom)?有点麻烦,但确实无需考虑正则表达式。
Or there is the library OpenCsv http://opencsv.sourceforge.net/ , which is commercial friendly. Apache 2.0 License
或者有OpenCsv http://opencsv.sourceforge.net/图书馆,它是商业友好的。 Apache 2.0许可证
#1
4
Just use the regular split(String, int)
method inside the String
class:
只需在String类中使用常规split(String,int)方法:
String line = "4000|name|state|city|zip||country|||address||";
String data[] = line.split("\\|", -1); // escaped, because of regular expressions
The minus one is a convention that indicates that the string will be split as you want it.
减号是一种约定,表示字符串将根据需要进行拆分。
#2
0
Yes to use split is obvious, but you may consider this options too:
是的,使用拆分是显而易见的,但你也可以考虑这个选项:
Why not just using string.indexOf("|", indexToStartFrom) ? Is a bit of hassle, but works for sure without having to think too much about regex.
为什么不使用string.indexOf(“|”,indexToStartFrom)?有点麻烦,但确实无需考虑正则表达式。
Or there is the library OpenCsv http://opencsv.sourceforge.net/ , which is commercial friendly. Apache 2.0 License
或者有OpenCsv http://opencsv.sourceforge.net/图书馆,它是商业友好的。 Apache 2.0许可证