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

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《java字符串转int方法(免费分享这4种转换方式)》的相关信息,《java字符串转int方法(免费分享这4种转换方式)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《java字符串转int方法(免费分享这4种转换方式)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

给定纯数字字符串类型数据如何转换为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种转换方式)

笨笨网美国主机,w ww.2 b p .n e t
提醒:《java字符串转int方法(免费分享这4种转换方式)》最后刷新时间 2025-03-21 11:13:39,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《java字符串转int方法(免费分享这4种转换方式)》该内容的真实性请自行鉴别。