Home »
Scala »
Scala Programs
Scala program to convert string to integer
Scala | Converting string to integer: Here, we are going to learn how to convert a given string to an integer in Scala programming language?
Submitted by Shivang Yadav, on April 21, 2020 [Last updated : March 10, 2023]
Scala – Converting String to Integer
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.
Scala code to convert string to integer
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
Scala String Programs »