Java中如何将字符串转换为整数

Java中如何将字符串转换为整数

技术背景

在Java编程中,经常会遇到需要将字符串类型的数据转换为整数类型的场景,例如从用户输入、文件读取或网络传输中获取的数据通常是字符串形式,而在程序中可能需要以整数形式进行计算和处理。因此,掌握字符串到整数的转换方法是很重要的。

实现步骤

1. 使用Integer.parseInt()方法

这是最常用的方法,它将字符串解析为有符号的十进制整数。

1
2
String myString = "1234";
int foo = Integer.parseInt(myString);

需要注意的是,该方法可能会抛出NumberFormatException异常,因此建议进行异常处理:

1
2
3
4
5
6
int foo;
try {
foo = Integer.parseInt(myString);
} catch (NumberFormatException e) {
foo = 0;
}

2. 使用Integer.valueOf()方法

该方法返回一个Integer对象。

1
2
String str = "1234";
Integer x = Integer.valueOf(str);

parseInt()的区别在于,valueOf()返回Integer对象,而parseInt()返回基本数据类型int

3. 使用Guava库的Ints方法结合Java 8的Optional

1
2
3
4
5
6
import com.google.common.primitives.Ints;
import java.util.Optional;

int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0);

4. 使用Apache Commons的NumberUtils

1
2
3
import org.apache.commons.lang3.math.NumberUtils;

int num = NumberUtils.toInt("1234");

如果字符串是无效的数字格式,toInt()方法将返回0,无需使用try-catch块。

5. 使用Integer.decode()方法

该方法可以处理八进制、十六进制等不同进制的字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// base 10
Integer.parseInt("12"); // 12 - int
Integer.valueOf("12"); // 12 - Integer
Integer.decode("12"); // 12 - Integer

// base 8
Integer.parseInt("12", 8); // 10 - int
Integer.valueOf("12", 8); // 10 - Integer
Integer.decode("012"); // 10 - Integer

// base 16
Integer.parseInt("12", 16); // 18 - int
Integer.valueOf("12", 16); // 18 - Integer
Integer.decode("#12"); // 18 - Integer
Integer.decode("0x12"); // 18 - Integer
Integer.decode("0X12"); // 18 - Integer

6. 手动实现转换方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public static int strToInt(String str) {
int i = 0;
int num = 0;
boolean isNeg = false;

// Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}

// Process each character of the string;
while (i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).
}

if (isNeg)
num = -num;

return num;
}

核心代码

以下是几种常用方法的核心代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import com.google.common.primitives.Ints;
import java.util.Optional;
import org.apache.commons.lang3.math.NumberUtils;

public class StringToIntConversion {
public static void main(String[] args) {
String str = "1234";

// 使用Integer.parseInt()
try {
int num1 = Integer.parseInt(str);
System.out.println("Integer.parseInt(): " + num1);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: " + e.getMessage());
}

// 使用Integer.valueOf()
Integer num2 = Integer.valueOf(str);
System.out.println("Integer.valueOf(): " + num2);

// 使用Guava库的Ints方法结合Optional
int num3 = Optional.ofNullable(str)
.map(Ints::tryParse)
.orElse(0);
System.out.println("Guava Ints + Optional: " + num3);

// 使用Apache Commons的NumberUtils
int num4 = NumberUtils.toInt(str);
System.out.println("Apache Commons NumberUtils: " + num4);
}
}

最佳实践

  • 异常处理:在使用Integer.parseInt()Integer.valueOf()等方法时,一定要进行异常处理,以防止程序因输入不合法的字符串而崩溃。
  • 选择合适的方法:根据具体需求选择合适的转换方法。如果需要处理不同进制的字符串,可以使用Integer.decode();如果希望在字符串无效时返回默认值,可以使用NumberUtils.toInt()
  • 性能考虑:在编程竞赛等对性能要求较高的场景中,可以手动实现解析方法,跳过验证代码以提高效率。

常见问题

  • NumberFormatException异常:当输入的字符串不是有效的整数格式时,Integer.parseInt()Integer.valueOf()等方法会抛出该异常。因此,在使用这些方法时,需要进行异常处理。
  • 数值范围问题:Java的int类型有最大值和最小值限制(Integer.MAX_VALUEInteger.MIN_VALUE),如果输入的字符串表示的数值超出了这个范围,也会抛出NumberFormatException异常。
  • 字符串格式问题:输入的字符串中不能包含非数字字符(除了开头的正负号),否则会抛出异常。例如,Integer.parseInt("1.1")Integer.parseInt("abc")都会抛出异常。

Java中如何将字符串转换为整数
https://119291.xyz/posts/2025-05-09.java-string-to-integer-conversion/
作者
ww
发布于
2025年5月9日
许可协议