Difference between split functions between char and string arguments

I try the following code in scala REPL:

"ASD-ASD.KZ".split('.') res7: Array[String] = Array(ASD-ASD, KZ) "ASD-ASD.KZ".split(".") res8: Array[String] = Array() 

Why does this function cause other results?

+6
source share
1 answer

There is a big difference in the use of the function.

The split function is overloaded, and this is an implementation from Scala source code:

/ ** For each line in this line:

  • Separate the main prefix consisting of spaces or control characters.
  • and then | out of line.

* /

  def stripMargin: String = stripMargin('|') private def escape(ch: Char): String = "\\Q" + ch + "\\E" @throws(classOf[java.util.regex.PatternSyntaxException]) def split(separator: Char): Array[String] = toString.split(escape(separator)) @throws(classOf[java.util.regex.PatternSyntaxException]) def split(separators: Array[Char]): Array[String] = { val re = separators.foldLeft("[")(_+escape(_)) + "]" toString.split(re) } 

So, when you call split() with char, you are asking to split this particular char:

 scala> "ASD-ASD.KZ".split('.') res0: Array[String] = Array(ASD-ASD, KZ) 

And when you call split() with a string, it means you want to have a regex. Therefore, to get the exact result using double quotes, you need to do:

 scala> "ASD-ASD.KZ".split("\\.") res2: Array[String] = Array(ASD-ASD, KZ) 

Where:

  • The first \ executes the next character
  • The second \ prints a character for a period, which is a regular expression, and we want to use it as a character
  • . - a character to divide the string into
+7
source

All Articles