Reputation: 3544
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 !
Upvotes: 4
Views: 103
Reputation: 1578
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)
Upvotes: 9
Reputation: 1153
If you will look in implementation of split you will notice that it checks for index of delimiter inside String, and if delimiter don't occur in given String it will result with String itself.
Upvotes: 0