简体   繁体   中英

difference between Split with a string and char argument in Scala?

Both String and Char arguments generate same output. What is the difference between Split with a string argument and char argument in Scala?

With String argument-

scala> "hello world".split(" ")
res0: Array[java.lang.String] = Array(hello, world)

With Char argument-

scala> "hello world".split(' ')
res1: Array[String] = Array(hello, world)

String argument inherited from Java class. Where as Char argument Scala use it's own class called StringLike Class. It means

scala> "hello world".split(" ")

using Split method from Java.

scala> "hello world".split(' ')

using Split method from Scala.

The version that takes a string interprets the string as a regex . This can lead to some highly confusing behavior. See for example

scala> "ab.cd".split(".")
res1: Array[java.lang.String] = Array()

"." is a regex that matches everything, so all characters are split characters and the result is emtpy. This is a questionable design decision in java.lang.String.

The scala extension method that takes a char matches just the literal char. So not only is it faster, but also more predictable:

scala> "ab.cd".split('.')
res2: Array[String] = Array(ab, cd)

In other words, when you are spliting with a character, "Hello world".split(' '), you are spliting the input with a single character. For example, you could split at "a, b, e, f", ect. However, when you are using the string method you can split the string with words, such as anytime the word "Cat" is displayed.

Therefore, You use "hello world".split(' ') when you are spliting the string with a single character.

If you are a genius spliting a gene into subgenes then you would use "Hello world.split("GTA") if you want everything inbetween the GTA gene GTACATFAGTAFADGTA.

Hope This helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM