Home » Scala programs » Scala string 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

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.

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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.