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.
在Scala中,有一个庞大的库来支持对字符串的不同操作。 一种这样的操作是在Scala中将字符串转换为int。
A string can be converted to integer in Scala using the toInt method.
可以使用toInt方法在Scala 中将字符串转换为整数。
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.
这将返回字符串的整数转换 。 如果字符串不包含整数,它将引发一个异常,该异常将为NumberFormatException 。
So, the statement: val i = "Hello".toInt will throw an exception instead of an integer.
因此,语句: val i =“ Hello” .toInt将引发异常而不是整数。
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.
因此,我们需要处理此异常,我们将使用try-catch块来执行此操作,并在要转换的字符串不包含整数值时显示“非整数的字符串” 。
在Scala中将字符串转换为整数的程序 (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
翻译自: https://www.includehelp.com/scala/convert-string-to-integer.aspx