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?

1
  • ""0,,,,," ... I would like to have 5 elements." 5 commas means 6 elements, if you retain them all. Commented Feb 11, 2016 at 14:44

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. How would you parse a csv file instead?
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, , ]

Comments

3

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

System.out.println("0,,,,,".split(",", -1).length); // Prints 6.

1 Comment

First argument of split is a String, not char ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.