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中,有一个庞大的库来支持对字符串的不同操作。 一种这样的操作是在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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值