在 Scala 中从 Array[String] 转换为 Seq[String]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42430118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 09:06:49  来源:igfitidea点击:

Converting from Array[String] to Seq[String] in Scala

scala

提问by ps0604

In the following Scala code I attempt to convert from a String that contains elements separated by "|" to a sequence Seq[String]. However the result is a WrappedArray of characters. How to make this work?

在以下 Scala 代码中,我尝试从包含由“|”分隔的元素的字符串进行转换 到一个序列Seq[String]。然而,结果是一个 WrappedArray 字符。如何使这项工作?

val array = "t1|t2".split("|")
println(array.toSeq)

results in:

结果是:

WrappedArray(t, 1, |, t, 2)

What I need is:

我需要的是:

Seq(t1,t2)

回答by rogue-one

The below works. ie split by pipe character ('|') instead of pipe string ("|"). since split("|")calls overloaded definitionthat takes an regex string where pipe is a meta-character. This gets you the incorrect result as shown in the question.

下面的作品。即由管道字符('|')而不是管道字符串(“|”)分割。因为split("|")调用了采用正则表达式字符串的重载定义,其中管道是元字符。如问题所示,这会为您提供不正确的结果。

scala> "t1|t2".split('|').toSeq
res10: Seq[String] = WrappedArray(t1, t2)