0fnt
0fnt

Reputation: 8661

Scala split behaviour: consecutive occurrence of split pattern

Using Scala's standard String library:

"a,,,".split( "," ) is

Array(a) , and not

Array( a, "", "", "" )

as one would expect. Is there any way to force this?

"a,,,b".split( "," ) is

Array( a, "", "", "", b ) which is fine.

I'd be surprised if this is a bug, so does anyone understand the purported logic behind this behaviour?

Upvotes: 3

Views: 555

Answers (1)

rtruszk
rtruszk

Reputation: 3922

In documentation of split method we can read:

Trailing empty strings are therefore not included in the resulting array.

But you can use split method with additional limit parameter. For example:

"a,,,".split( "," ,-1)

Setting negative number as limit parameter will cause that pattern will be applied as many times as possible.

See here for details

Upvotes: 8

Related Questions