scala 如何在scala中将字符串数组转换为int数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29883814/
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 07:05:42  来源:igfitidea点击:

How to convert string array to int array in scala

scalatypescasting

提问by Mohammad Gharehyazie

I am very new to Scala, and I am not sure how this is done. I have googled it with no luck. let us assume the code is:

我对 Scala 很陌生,我不确定这是如何完成的。我没有运气就用谷歌搜索了它。让我们假设代码是:

var arr = readLine().split(" ")

Now arr is a string array. Assuming I know that the line I input is a series of numbers e.g. 1 2 3 4, I want to convert arr to an Int (or int) array.

现在 arr 是一个字符串数组。假设我知道我输入的行是一系列数字,例如 1 2 3 4,我想将 arr 转换为 Int(或 int)数组。

I know that I can convert individual elements with .toInt, but I want to convert the whole array.

我知道我可以使用 .toInt 转换单个元素,但我想转换整个数组。

Thank you and apologies if the question is dumb.

如果问题很愚蠢,谢谢并道歉。

回答by Marth

Applying a function to every element of a collection is done using .map:

将函数应用于集合的每个元素是使用.map以下方法完成的:

scala> val arr = Array("1", "12", "123")
arr: Array[String] = Array(1, 12, 123)

scala> val intArr = arr.map(_.toInt)
intArr: Array[Int] = Array(1, 12, 123)

Note that the _.toIntnotation is equivalent to x => x.toInt:

请注意,该_.toInt符号等效于x => x.toInt

scala> val intArr = arr.map(x => x.toInt)
intArr: Array[Int] = Array(1, 12, 123)


Obviously this will raise an exception if one of the element is not an integer :

显然,如果元素之一不是整数,这将引发异常:

scala> val arr = Array("1", "12", "123", "NaN")
arr: Array[String] = Array(1, 12, 123, NaN)

scala> val intArr = arr.map(_.toInt)
java.lang.NumberFormatException: For input string: "NaN"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:580)
  at java.lang.Integer.parseInt(Integer.java:615)
  at scala.collection.immutable.StringLike$class.toInt(StringLike.scala:272)
  ...
  ... 33 elided

回答by Xavier Guihot

Starting Scala 2.13, you might want to use String::toIntOptionin order to safely cast Strings to Option[Int]s and thus also handle items that can't be cast:

从 开始Scala 2.13,您可能想要使用String::toIntOption以安全地将Strings 强制转换为Option[Int]s,从而也处理无法强制转换的项目:

Array("1", "12", "abc", "123").flatMap(_.toIntOption)
// Array[Int] = Array(1, 12, 123)