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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With