在这个教程中,我们将学习如何在 Java 中将String转换为int。如果字符串由1,2,3等数字组成,则在将其转换为整数值之前,不能对其执行任何算术运算。在本教程中,我们将看到两种将String转换为int的方法 –
- 使用Integer.parseInt(String)方法将字符串转换为int使用Integer.valueOf(String)方法将String转换为int
使用Integer.parseInt(String)将String转换为int
Integer包装类的parseInt()方法将字符串解析为有符号整数。这就是我们进行转换的方式 –
这里我们有一个字符串str,其值为"1234",方法parseInt()将str作为参数,并在解析后返回整数值。
String str = "1234";int inum = Integer.parseInt(str);
让我们看看完整的例子 –
使用Integer.parseInt(String)将String转换为int
public class JavaExample{ public static void main(String args[]){ String str="123"; int inum = 100; /* converting the string to an int value * ,the value of inum2 would be 123 after * conversion */ int inum2 = Integer.parseInt(str); int sum = inum+inum2; System.out.println("Result is: "+sum); }}输出:

让我们看一下String到int转换的另一个有趣的例子。
将String转换为带有前导零的int
在这个例子中,我们有一个由带有前导零的数字组成的字符串,我们想对保留前导零的字符串执行算术运算。为此,我们将字符串转换为int并执行算术运算,稍后我们将使用format()方法将输出值转换为字符串。
public class JavaExample{ public static void main(String args[]){ String str="00000678"; /* String to int conversion with leading zeroes * the %08 format specifier is used to have 8 digits in * the number, this ensures the leading zeroes */ str = String.format("%08d", Integer.parseInt(str)+102); System.out.println("Output String: "+str); }}输出:

