繁体   English   中英

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

[英]Converting string to a collection of digits in Scala using map and toInt

我可以使用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 (-集合)的元素是一个Char -因此只需再次创建一个String

或使用他建议的.asDigit

"123".map(_.asDigit)

从Repl:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM