Q:

Scala program to convert string to integer

belongs to collection: Scala String Programs

0

In Scala, there is a huge library to support different operations on a string. One such operation is to convert string to int in Scala.

A string can be converted to integer in Scala using the toInt method.

Syntax:

    string.toInt

This will return the integer conversion of the string. If the string does not contain an integer it will throw an exception with will be NumberFormatException.

So, the statement: val i = "Hello".toInt will throw an exception instead of an integer.

So, we need to handle this exception and we will do this using the try-catch block and print "The string in not integer" when the string to be converted does not contain an integer value.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to convert string to integer in Scala

object MyClass {
       def main(args: Array[String]) {
        val string = "1C 2C++ 3Java"
        println(string)
        
        val stringContents = string.split("\\d+")
        
        println("Content of the string are: ")
        
        for(i <- 0 to stringContents.length-1)
            println(stringContents(i))
    }
}

Output

The string is : 12345
Integer Conversion of string is 12345

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to count the number of characters in a string ... >>
<< Scala program to split string...