string转int详解(4种常用方法)

string转int详解(4种常用方法)-mikechen

将string转int是Java开发经常使用到的,下面就介绍4种常见的string转int方法@mikechen

使用 parseInt() 方法

可以使用Integer.parseInt() 方法,将字符串转换为整数。

如下所示:

String strNum = "123";
try {
    int num = Integer.parseInt(strNum);
    System.out.println("转换后的整数为: " + num);
} catch (NumberFormatException e) {
    System.out.println("无法将字符串转换为整数");
}

Integer.parseInt() 接受一个字符串作为参数,然后返回一个整数。

如果字符串不能被解析为整数,它会抛出一个 NumberFormatException 异常。

 

使用valueOf() 方法

Integer.valueOf() 方法也可以将字符串转换为整数,但它返回一个 Integer 对象而不是一个原始的 int。

如下所示:

String strNum = "123";
try {
    Integer integer = Integer.valueOf(strNum);
    int num = integer.intValue(); // 自动拆箱
    System.out.println("转换后的整数为: " + num);
} catch (NumberFormatException e) {
    System.out.println("无法将字符串转换为整数");
}

如果字符串不能被解析为整数,它会抛出 NumberFormatException 异常。

 

使用Scanner 类

Scanner 类可以用于从字符串中提取整数值,如下所示:

import java.util.Scanner;

String strNum = "123";
Scanner scanner = new Scanner(strNum);
if (scanner.hasNextInt()) {
    int num = scanner.nextInt();
    System.out.println("转换后的整数为: " + num);
} else {
    System.out.println("无法将字符串转换为整数");
}
scanner.close();

这个方法,可以处理包含空格和其他非数字字符的字符串。

 

使用正则表达式

还可以使用正则表达式,来检查字符串是否包含整数。

如下所示:

import java.util.regex.*;

String strNum = "123";
Pattern pattern = Pattern.compile("\\d+"); // 匹配一个或多个数字
Matcher matcher = pattern.matcher(strNum);

if (matcher.matches()) {
    int num = Integer.parseInt(matcher.group());
    System.out.println("转换后的整数为: " + num);
} else {
    System.out.println("无法将字符串转换为整数");
}

这种方法,允许您更灵活地处理字符串。

这些是在Java中将String转换为int的常见方法,你可以根据您的具体需求和输入数据的格式选择合适的方法。

作者简介

陈睿|mikechen,10年+大厂架构经验,就职于阿里巴巴、淘宝、百度等一线互联网大厂。

关注作者「mikechen」公众号,获取更多技术干货!

评论交流
    说说你的看法