Groovy字符串为int [英] Groovy String to int
问题描述
我有一个字符串
,它表示一个整数值,并希望将它转换为 int
。是否有一个相当于Java的 Integer.parseInt(String)
?
使用 toInteger()
方法将 String
转换为整数
,例如
int value =99.toInteger()
另一种避免使用不赞成使用方法的方法是(见下文)
pre > int value =66as Integer
如果您需要检查是否在执行转换之前可以转换字符串
can ,使用
String number =66
if(number.isInteger()){
int value = number as Integer
}
$如果你在一个Grails控制器中转换一个请求参数的话, ,还有一个更好的办法:
$ p $ 整数paramValue = params.int('paramName')
这种技术的一个很好的特性是它是安全的,即如果参数不能转换为 Integer
,它将返回null而不是抛出异常。
弃用更新
在最近的Groovy版本中, toInteger()
方法已被弃用。以下内容取自Groovy 2.4.4中的 org.codehaus.groovy.runtime.StringGroovyMethods
/ **
*将一个CharSequence解析为一个整数
*
* @param self a CharSequence
* @return一个整数
* @因为1.8.2
* /
public static Integer toInteger(CharSequence self){
return Integer.valueOf(self.toString()。trim());
}
/ **
* @deprecated使用CharSequence版本
* @see #toInteger(CharSequence)
* /
@弃用
public static Integer toInteger(String self){
return toInteger((CharSequence)self);
$ / code>
您可以强制使用某种方法调用未弃用的方法版本可怕的是:
int num =((CharSequence)66)。toInteger()
我个人更喜欢:
int num = 66 as Integer
I have a String
that represents an integer value and would like to convert it to an int
. Is there a groovy equivalent of Java's Integer.parseInt(String)
?
Use the toInteger()
method to convert a String
to an Integer
, e.g.
int value = "99".toInteger()
An alternative, which avoids using a deprecated method (see below) is
int value = "66" as Integer
If you need to check whether the String
can be converted before performing the conversion, use
String number = "66"
if (number.isInteger()) {
int value = number as Integer
}
Grails
If you're converting a request parameter in a Grails controller, there's an even better way
Integer paramValue = params.int('paramName')
One of the nice features of this technique is that it's safe, i.e. if the parameter cannot be converted to an Integer
it returns null rather than throwing an exception.
Deprecation Update
In recent versions of Groovy one of the toInteger()
methods has been deprecated. The following is taken from org.codehaus.groovy.runtime.StringGroovyMethods
in Groovy 2.4.4
/**
* Parse a CharSequence into an Integer
*
* @param self a CharSequence
* @return an Integer
* @since 1.8.2
*/
public static Integer toInteger(CharSequence self) {
return Integer.valueOf(self.toString().trim());
}
/**
* @deprecated Use the CharSequence version
* @see #toInteger(CharSequence)
*/
@Deprecated
public static Integer toInteger(String self) {
return toInteger((CharSequence) self);
}
You can force the non-deprecated version of the method to be called using something awful like:
int num = ((CharSequence) "66").toInteger()
Personally, I much prefer:
int num = 66 as Integer
这篇关于Groovy字符串为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!