简体   繁体   English

在Scala中使用字符串拆分和char参数之间的区别?

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

Both String and Char arguments generate same output. String和Char参数都生成相同的输出。 What is the difference between Split with a string argument and char argument in Scala? Scala中带字符串参数的split和char参数有什么区别?

With String argument- 使用String参数-

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

With Char argument- 使用Char参数-

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

String argument inherited from Java class. 从Java类继承的String参数。 Where as Char argument Scala use it's own class called StringLike Class. 作为Char参数Scala使用的是它自己的类,称为StringLike类。 It means 它的意思是

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

using Split method from Java. 使用Java的Split方法。

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

using Split method from Scala. 使用Scala中的Split方法。

The version that takes a string interprets the string as a regex . 接受字符串的版本将字符串解释为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. 这是java.lang.String中有疑问的设计决策。

The scala extension method that takes a char matches just the literal char. 采用char的scala扩展方法仅与文字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. 换句话说,当使用字符“ Hello world” .split('')进行拆分时,将使用单个字符拆分输入。 For example, you could split at "a, b, e, f", ect. 例如,您可以分割为“ a,b,e,f”等。 However, when you are using the string method you can split the string with words, such as anytime the word "Cat" is displayed. 但是,当您使用字符串方法时,可以用单词分割字符串,例如在显示“ Cat”一词的任何时候。

Therefore, You use "hello world".split(' ') when you are spliting the string with a single character. 因此,在用单个字符分割字符串时,请使用“ hello world” .split('')。

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. 如果您是一个天才,可以将一个基因拆分为多个子基因,那么如果您希望介于GTA基因GTACATFAGTAFADGTA之间的所有内容,都可以使用“ Hello world.split(“ GTA”)。

Hope This helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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