Arturs Vancans
Arturs Vancans

Reputation: 4640

How to split string with trailing empty strings in result?

I am a bit confused about Scala string split behaviour as it does not work consistently and some list elements are missing. For example, if I have a CSV string with 4 columns and 1 missing element.

"elem1, elem2,,elem 4".split(",") = List("elem1", "elem2", "", "elem4")

Great! That's what I would expect.

On the other hand, if both element 3 and 4 are missing then:

"elem1, elem2,,".split(",") = List("elem1", "elem2")

Whereas I would expect it to return

"elem1, elem2,,".split(",") = List("elem1", "elem2", "", "")

Am I missing something?

Upvotes: 37

Views: 12280

Answers (2)

Alex K
Alex K

Reputation: 8338

As Peter mentioned in his answer, "string".split(), in both Java and Scala, does not return trailing empty strings by default.

You can, however, specify for it to return trailing empty strings by passing in a second parameter, like this:

String s = "elem1,elem2,,";
String[] tokens = s.split(",", -1);

And that will get you the expected result.

You can find the related Java doc here.

Upvotes: 69

peterremec
peterremec

Reputation: 516

I believe that trailing empty spaces are not included in a return value.

JavaDoc for split(String regex) says: "This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array."

So in your case split(String regex, int limit) should be used in order to get trailing empty string in a return value.

Upvotes: 4

Related Questions