ImbaBalboa
ImbaBalboa

Reputation: 867

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

Upvotes: 1

Views: 121

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201537

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.

Upvotes: 3

flavian
flavian

Reputation: 28511

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

Upvotes: 7

Related Questions