Fishsticks Fishsticks - 2 months ago 7
Scala Question

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.

Answer

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.