小樱知识 > 生活常识java字符串转int方法(免费分享这4种转换方式)

java字符串转int方法(免费分享这4种转换方式)

提问时间:2022-03-16 14:54:07来源:小樱知识网


给定纯数字字符串类型数据如何转换为int类型,这里以字符串 “9527” 为例子进行转换!

方式一、

使用Integer 的 parseInt方式进行转换:

String str=”9527″;

int foo =Integer.parseInt(str);

// 此转换会引发 NumberFormatException 异常可以进行catch处理,改造后代码如下:

String str=”9527″;

int foo;

try{

foo =Integer.parseInt(str);

}catch(NumberFormatException e){

// 出现异常返回: 0

foo =0;

}

方式二、

使用Integer 的 valueOf方式进行转换:

String str=”9527″;

int foo =Integer.valueOf(str);

valueOf 与 parseInt之间略有不同,区别如下:

  • valueOf 返回的新实例或缓存实例 java.lang.Integer
  • parseInt 返回原始值 int

方式三、

使用Google的 Guava 库,代码如下:

import com.google.common.primitives.Ints;

String str=”9527″;

int foo =Optional.ofNullable(str)

.map(Ints::tryParse)

.orElse(0)

使用此方法尝试转换,成功返回具体的值,失败返回0

方式四、

使用commons-lang3提供的方法,代码如下:

String str=”9527″;

int foo1 =NumberUtils.toInt(str)

// defaultValue 是转换失败时的默认值

int foo2 =NumberUtils.toInt(str, defaultValue)

方式五、

其他方式,代码如下:

String str=”9527″;

int foo1 = Integer.decode(str);

int foo2 = Integer.parseUnsignedInt(str);

你这4种转换方式)

以上内容就是为大家推荐的java字符串转int方法(免费分享这4种转换方式)最佳回答,如果还想搜索其他问题,请收藏本网站或点击搜索更多问题

内容来源于网络仅供参考
二维码

扫一扫关注我们

版权声明:所有来源标注为小樱知识网www.xiaoyin02.com的内容版权均为本站所有,若您需要引用、转载,只需要注明来源及原文链接即可。

本文标题:java字符串转int方法(免费分享这4种转换方式)

本文地址:https://www.xiaoyin02.com/shcs/122473.html

相关文章