Scala程序将字符串转换为整数
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中,有一個(gè)龐大的庫來支持對字符串的不同操作。 一種這樣的操作是在Scala中將字符串轉(zhuǎn)換為int。
A string can be converted to integer in Scala using the toInt method.
可以使用toInt方法在Scala 中將字符串轉(zhuǎn)換為整數(shù)。
Syntax:
句法:
string.toIntThis 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.
這將返回字符串的整數(shù)轉(zhuǎn)換 。 如果字符串不包含整數(shù),它將引發(fā)一個(gè)異常,該異常將為NumberFormatException 。
So, the statement: val i = "Hello".toInt will throw an exception instead of an integer.
因此,語句: val i =“ Hello” .toInt將引發(fā)異常而不是整數(shù)。
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塊來執(zhí)行此操作,并在要轉(zhuǎn)換的字符串不包含整數(shù)值時(shí)顯示“非整數(shù)的字符串” 。
在Scala中將字符串轉(zhuǎn)換為整數(shù)的程序 (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
總結(jié)
以上是生活随笔為你收集整理的Scala程序将字符串转换为整数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3dmax批量导入obj_ArcGIS
- 下一篇: Java中lastValue_在Logs