Scala 将逗号分隔的字符串转为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19748986/
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
Scala turn comma delimited string to Array
提问by randombits
I have a string that looks like the following:
我有一个如下所示的字符串:
"1,100,53,5000,23,3,3,4,5,5"
"1,100,53,5000,23,3,3,4,5,5"
I want to simply turn this into a Array of distinct Integer elements. Something that would look like:
我想简单地把它变成一个不同的整数元素的数组。看起来像这样的东西:
Array(1, 100, 53, 5000, 23, 3, 4, 5)
Is there a Stringmethod in Scala that would help with this?
StringScala 中有一种方法可以帮助解决这个问题吗?
回答by Marth
scala> "1,100,53,5000,23,3,3,4,5,5".split(",").map(_.toInt).distinct
res1: Array[Int] = Array(1, 100, 53, 5000, 23, 3, 4, 5)
Obviously this raises an exception if one of the value in the array isn't an integer.
显然,如果数组中的值之一不是整数,则会引发异常。
edit: Hadn't seen the 'distinct numbers only' part, fixed my answer.
编辑:没有看到“仅不同数字”部分,修复了我的答案。
回答by kompot
Another version that deals nicely with non parseable values and just ignores them.
另一个版本可以很好地处理不可解析的值并忽略它们。
scala> "1,100,53,5000,will-not-fail,23,3,3,4,5,5".split(",").flatMap(maybeInt =>
scala.util.Try(maybeInt.toInt).toOption).distinct
res2: Array[Int] = Array(1, 100, 53, 5000, 23, 3, 4, 5)
回答by Stefan Kunze
added type checking for the string being parseable as Int :
为可解析为 Int 的字符串添加了类型检查:
package load.data
object SplitArray {
def splitArrayintoString(s: String): Set[Int] =
{
val strArray = s.split(",")
strArray filter isParseAbleAsInt map (_.toInt) toSet
}
private def isParseAbleAsInt(str: String): Boolean =
str.forall(Character.isDigit(_))
}
回答by Xavier Guihot
Starting Scala 2.13, if you expect items that can't be cast, you might want to use String::toIntOptionin order to safely cast these split Strings to Option[Int]s and eliminate them with a flatMap:
开始Scala 2.13,如果您希望无法投射的项目,您可能想要使用String::toIntOption以安全地将这些 split Strings 转换为Option[Int]s 并使用 a 消除它们flatMap:
"1,100,53s,5000,4,5,5".split(',').flatMap(_.toIntOption).distinct
// Array[Int] = Array(1, 100, 5000, 4, 5)

