Java中字符串转int数据类型的三种方式

字符串转int数据类型的三种方式

方法一: Integer.valueOf( )

它将返回一个包装器类型 Integer,当然可以通过自动拆箱的方式将其转成 int 类型。

String a = "100";
String b= "50";
int A = Integer.valueOf(a);
int B = Integer.valueOf(b);
 
int c = A+B;
System.out.println(c);

方法二: Integer.parseInt(),它将返回一个基本数据类型 int。

String a = "100";
String b= "50";
int A = Integer.parseInt(a);
int B = Integer.parseInt(b);
 
int c = A+B;
System.out.println(c);

这两种方式,优先推荐第二种,因为不涉及到自动拆箱,性能更佳。

方法三:

public class String2IntDemo {
    public static void main(String[] args) {
        String a = "100";
        String b = "50";
        int A = string2int(a);
        int B = string2int(b);
        int c = A + B;
        System.out.println(c);
    }
 
    public static int string2int(String s) {
        int num = 0;
        int pos = 1;
        for (int i = s.length() - 1; i >= 0; i--) {
            num += (s.charAt(i) - '0') * pos;
            pos *= 10;
 
        }
        return num;
 
    }
}

所有的字符都有识别它们的代码——这代码就是 ASCII 码。

基于这一点,所有数字型的字符减去字符‘0’,将会得到该字符的绝对值,是一个整数。

示例:

String s = "520";
System.out.println(s.charAt(2) - '0');
System.out.println(s.charAt(1) - '0');
System.out.println(s.charAt(0) - '0');

输出结果如下所示:

0

2

5

字符串“520”的长度为 3,也就是说,下标为 2 的位置是字符‘0’——数字 520 的个位数;下标为 1 的位置是字符‘2’——数字 520 的十位数;下标为 0 的位置是字符‘5’——数字 520 的百位数。

通过一个 for 循环,遍历一下字符串,然后计算出当前位置上的整数值,个位数乘以 1,十位数乘以 10,百位数乘以 100,然后再加起来,就是字符串对应的整数值了。

原文地址:https://blog.csdn.net/yiXin_Chen/article/details/123405429