我可以使用 toInt
将单个数字字符串转换为 int:
scala> "1".toInt
res1: Int = 1
但是,当我使用 map
迭代字符并使用 toInt
单独转换它们时,我得到了它们的 ASCII 代码:
scala> "123".map(_.toInt)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(49, 50, 51)
为什么会这样?是否可以使用 map
和 toInt
来完成此任务?
最佳答案
只需在 map
函数中添加 toString
即可:
"123".map(_.toString.toInt)
正如Xavier所解释的那样,String
(-collection)的元素是一个Char
- 所以只需创建一个String
再次。
或者按照他的建议使用.asDigit
:
"123".map(_.asDigit)
来自回复:
scala> "123".map(_.toInt)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(49, 50, 51)
scala> "123".map(_.toString.toInt)
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
scala> "123".map(_.asDigit)
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3)
关于string - 使用 map 和 toInt 将字符串转换为 Scala 中的数字集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56667654/