2

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?

2
  • You could always do a replaceAll("::",": :") Commented Jan 20, 2016 at 15:33
  • Possible duplicate of String Split in Scala Commented Jan 20, 2016 at 17:38

1 Answer 1

4

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.

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

1 Comment

Thamk you for the detailed answer :)

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.