string - 使用 map 和 toInt 将字符串转换为 Scala 中的数字集合

标签 string scala type-conversion int

我可以使用 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)

为什么会这样?是否可以使用 maptoInt 来完成此任务?

最佳答案

只需在 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/

相关文章:

r - 将向量列表转置为来自 data.frame

c - 无法检查 C 中 argv[] 中的第二个字符

PHP:删除多维数组中的空数组字符串

c - 修改堆栈中字符串的算法

scala - 柯里化(Currying)和高阶函数之间的区别

bash - 如何执行solr zookeeper CLI上传solr配置

c# - 如何创建实现少量接口(interface)(或接口(interface)子集)的类型变量?

c - 使用 printf to printf 打印字符串的一部分

scala - 如何设置使用 JDBC 数据源写入 MySQL 表的字符集?

c# - 将字符串变量值转换为文字