给一个 String str="123"; 转成 int 类型数据
面试的时候问这个问题,可能考察的不仅仅是 parseInt()、valueOf()、intValue 等方法
这个面试官想要的答案我也没不明白 这里写几种转换方式(转换时不考虑字符串非数字)
一、parseInt
public int String2Int01(String str){ return Integer.parseInt(str);}
复制代码
二、valueOf intValue
public int String2Int02(String str){ return Integer.valueOf(str).intValue(); }
复制代码
三、 new Integer(String str)
public int String2Int03(String str){ return new Integer(str).intValue();}// 可以看源码 用的还是parseInt() public Integer(String s) throws NumberFormatException { this.value = parseInt(s, 10); }
复制代码
四、转数组 再位数求和
public int String2Int04(String str){ char[] chars = str.toCharArray(); int res = 0; int basic= 1;// 基数1 每次累计*10 // 比如 123 分解开就是 3*1 + 2*10 + 1*100 for (int i = chars.length-1; i >= 0; i--) { // - '0' 是把char转换为0-9s res= res + (chars[i]-'0')*basic; basic = basic*10; } return res;}
复制代码
评论