Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Split behaves differently on different Strings?

Here are the two cases :

Case 1:

scala> "".split('f')
res3: Array[String] = Array("")

Case 2:

scala> "f".split('f')
res5: Array[String] = Array()

Why does it behaves diffently here ! A concrete explanation would be great !

like image 956
Shivansh Avatar asked Jan 06 '23 04:01

Shivansh


1 Answers

In first case you provide a string and a separator that doesn't match any of characters in that string. So it just returns the original string. This can be illustrated with non-empty string example:

scala> "abcd".split('f')
res2: Array[String] = Array(abcd)

However your second string contains only separator. So it matches the separator and splits the string. Since splits contain nothing - it returns an empty array. According to Java String docs:

If expression doesn't match:

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

If expression matches:

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

Source: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)

like image 147
Zyoma Avatar answered Jan 10 '23 20:01

Zyoma