1

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.

4
  • Can you please give an example input, i.e. "1234" should return the number, 1234? Commented Oct 7, 2016 at 15:22
  • Thanks Kevin, I solved the problem. asDigit was what I was looking for. I wanted 1234 to become 1 and 2 and 3 and 4 so I could process each digit separately. I was getting 49, 50, 51, etc. It would have been easy enough to subtract ascii zero but I felt that would be a poor start to my budding Scala career if I stooped that low. Commented Oct 7, 2016 at 15:27
  • How should negative numbers be handled? In other words, what's the output of -1234? Commented Oct 7, 2016 at 15:35
  • For my problem there was no need to handle anything but digits, so the solution is adequate. I'm using Alvin Alexander's Scala Cookbook as a guide. For your question I can use Integer.parseInt("-1234", 10) (assuming base 10). Thanks for asking. Commented Oct 9, 2016 at 17:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

asDigit is the answer. Many thanks. I found the question has been asked before: stackoverflow.com/questions/16241923/… I didn't see it because I searched for string and not char.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.