6

I have a data file in csv format. I am trying to split each line using the basic split command line.split(',') But when I get a string like this "2,,", instead of returning an array as thus Array(2,"","") I just get an Array: Array(2). I am most definitely missing something basic, could someone help point out the correct way to split a comma separated string here?

0

1 Answer 1

11

This is inherited from Java. You can achieve behavior you want by using the split(String regex, int limit) overload:

"2,,".split(",", -1) // = Array(2, "", "")

Note the String instead of Char.

As explained by the Java Docs, the limit parameter is used as follows:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Source

Using split(separator: Char) will call the overload above, using a limit of zero.

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

2 Comments

Thank You LimbSoup, But what's the use of the limit variable?
Edited my response to include the explanation from the java docs. It's a bit long.

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.