Fishsticks Fishsticks - 1 year ago 100
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 Source

One possible solution is:

for(in <- lines) { { i =>
        if(i == 1) {
            //do stuff

And more compact w/ output:

lines.foreach(in => == 1).foreach(i => println(s"found $i in $in.")))

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download