0

I'm reading from a .csv File line by line. One line could look for example as following: String str = "10,1,,,,".

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.

Another example is String str = "0,,,,," which results in only one element but I would like to have 5 elements.

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.

How can this be done?

machinery
  • 5,972
  • 12
  • 67
  • 118

3 Answers3

5

You need to use it with -1 parameter

String[] splitted = str.split(",", -1);

This has been discussed before, e.g. Java: String split(): I want it to include the empty strings at the end

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 would split the row into 4 parts:

[23, "test, test", "123.88"]

and I don't think you want that.

Community
  • 1
  • 1
radoh
  • 4,554
  • 5
  • 30
  • 45
  • Thank you for your answer. How would you parse a csv file instead? – machinery Feb 11 '16 at 15:04
  • I'd look for some library http://stackoverflow.com/questions/101100/csv-api-for-java or http://stackoverflow.com/questions/843997/csv-parsing-in-java-working-example – radoh Feb 11 '16 at 15:05
3

split only drops trailing delimeters by default. You can turn this off with

String str = "9,,,1,,";
String[] parts = str.split(",", -1);
System.out.println(Arrays.toString(parts));

prints

[9, , , 1, , ]
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
3

Pass -1 (or any negative number, actually) as a second parameter to split:

System.out.println("0,,,,,".split(",", -1).length); // Prints 6.
Andy Turner
  • 137,514
  • 11
  • 162
  • 243