Fred
Fred

Reputation: 579

Scala: convert each digit in a string to an integer

I want to convert each digit in a number to an int. Here is my code

for (in <- lines) { 
    for (c <- in) {
        val ci = c.toInt
        if (ci == 0) {
            // do stuff
        }
    }
}

The result I get is the ascii code, i.e. a 1 gives 49. I'm looking for the value 1. The answer is trivial, I know. I'm trying to pull myself up with my own bootstraps until my Scala course begins in two weeks. Any assistance gratefully accepted.

Upvotes: 1

Views: 1080

Answers (2)

Mitchell Schwitzer
Mitchell Schwitzer

Reputation: 98

One possible solution is:

for(in <- lines) {
    in.toString.map(_.asDigit).foreach { i =>
        if(i == 1) {
            //do stuff
        }
    }
}

And more compact w/ output:

lines.foreach(in => in.toString.map(_.asDigit).filter(_ == 1).foreach(i => println(s"found $i in $in.")))

If lines is already a collection of Strings, omit the .toString on in.toString.

Upvotes: 1

Leo Bufi Barrameda
Leo Bufi Barrameda

Reputation: 359

You can have this:

val number = 123456
//convert Int to String and do transformation for each character to Digit(Int)
val digitsAsList = number.toString.map(_.asDigit)

This will result to digitizing the number. Then with that Collection, you can do anything from filtering, mapping, zipping: you can checkout the the List api on this page: http://www.scala-lang.org/api/2.11.8/#scala.collection.immutable.List

Hope that's help.

Upvotes: 1

Related Questions