任意字符转换为数字
原创
©著作权归作者所有:来自51CTO博客作者曲乐幽香的原创作品,请联系作者获取转载授权,否则将追究法律责任
1.Integer.parseInt()
"123";
int b = Integer.parseInt(aString);
System.out.println(b + "");
2.转换为字符串数组再运算
package com.lizi.demo;
public class String2Int {
public static void main(String[] args) {
String aString = "123";
int b = Integer.parseInt(aString);
System.out.println(b + "");
// 方法二
// 1.字符串转换成数组 string.toCharArray();
// 2.遍历字符型数组,每一位与'0'作减法,存入数值型数组
// Ingeter[] ints = new Integer[s.length];
// ints[i] = c[i] - '0';
// 3.遍历相减得到的数组,每位*(10^(length-1))
String2Int string2Int = new String2Int();
string2Int.StringToInt(aString);
}
public void StringToInt(String string) {
char[] c = string.toCharArray();
Integer[] intLength = new Integer[c.length];
for (int i = 0; i < c.length; i++) {
intLength[i] = c[i] - '0';
}
Double result = 0D;
for (int i = 0; i < intLength.length; i++) {
result += (intLength[i] * Math.pow(10, (intLength.length - 1 - i)));
}
Integer n = result.intValue();
System.out.println(n + "");
}
}