在 Groovy 中将字符串转换为 int [英] Converting a string to int in Groovy

查看:120
本文介绍了在 Groovy 中将字符串转换为 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 String 代表一个整数值,并希望将其转换为 int.是否有 Java 的 Integer.parseInt(String) 的 groovy 等价物?

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)?

推荐答案

使用 toInteger() 方法将 String 转换为 Integer>,例如

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

如果在执行转换前需要检查String 是否可以转换,使用

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
}

弃用更新

在 Groovy 的最新版本中,toInteger() 方法之一已被弃用.以下摘自 Groovy 2.4.4 中的 org.codehaus.groovy.runtime.StringGroovyMethods

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆