简体   繁体   中英

List string int converting in scala

I am confused about list of chars and int with scala. Here is my example :

scala> var s = "123456"
s: String = 123456

scala> s.map(_.toInt)
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(49, 50, 51, 52, 53, 54)

scala> s.map(_.toInt).sum
res1: Int = 309

The chars are converted in ASCII code I assume, how to just transform a char in its value ?

Thank you

s.map(_.asDigit).sum is the correct Scala API method. The toInt will return the ASCI code of the symbol, instead of the numerical representation.

scala> "123456".map(_.asDigit).sum
res0: Int = 21

You can use Character.getNumericValue(char) like

s.map(Character.getNumericValue(_))

Outputs

res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6)

Another option, would be subtracting '0' like

s.map(_ - '0')

for the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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