Pop
Pop

Reputation: 12401

Splitting strings in scala

I have spotted this "strange" behavior in the scala function split of class string:

"a:b::".split(":") returns Array[String] = Array(a, b)

Instead, I would like to get Array[String] = Array(a, b, "", "")

Do you have an idea to get such a response?

Upvotes: 2

Views: 1393

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

Use the limit parameter with -1:

scala> "a:b::".split(":", -1)
res1: Array[String] = Array(a, b, "", "")

There is a longer overload with the signature split(regex: String, limit: Int), but you're using the overload with only the regex argument, which calls the former overload with a limit of zero. When the limit is zero, empty strings are discarded from the end of the array.

From the javadoc:

If n [limit] 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.

Upvotes: 4

Related Questions