我有一个字符串,表示一个整数值,并希望将其转换为int。groovy中是否有类似于Java的Integer.parseInt(String)?


当前回答

这是另一种方法。如果你不喜欢异常。

def strnumber = "100"
def intValue = strnumber.isInteger() ?  (strnumber as int) : null

其他回答

def str = "32"

int num = str as Integer

作为Don回答的补充,groovy不仅为Strings添加了. tointeger()方法,还添加了toBigDecimal()、toBigInteger()、toBoolean()、toCharacter()、toDouble()、toFloat()、toList()和toLong()。

同样,groovy还添加了is* eqivalents,如果所讨论的String可以解析为所讨论的格式,则返回true。

相关的GDK页面在这里。

toInteger()方法在groovy中是可用的,您可以使用它。

你也可以进行静态导入

import static java.lang.Integer.parseInt as asInteger

在这之后

String s = "99"
asInteger(s)

这是另一种方法。如果你不喜欢异常。

def strnumber = "100"
def intValue = strnumber.isInteger() ?  (strnumber as int) : null