本文共 3899 字,大约阅读时间需要 12 分钟。
字符串转int整型代码如下:
//将数值型字符串通过包装类Integer转为int整型 String n=“123”; int num=Integer.parseInt(n); System.out.println(“num为:”+num); 字符串转整型的三种方式如下: parseInt内部底层实现:先比较要转的字符是否为空,然后判断进制radix是否在最小进制2到最大进制36之间,如果格式不正确返回异常(数据格式异常)NumberFormatExceptioncharAt方法可以定位一个String类型变量的某个索引单元的元素,括号内的参数是String类型变量的索引,charAt方法获得指定索引处的字符数据。
ParseInt()底层代码:将数值型字符串转换为整型public static int parseInt(String s, int radix) throws NumberFormatException { /* * WARNING: This method may be invoked early during VM initialization * before IntegerCache is initialized. Care must be taken to not use * the valueOf method. */ if (s == null) { throw new NumberFormatException("null"); } if (radix < Character.MIN_RADIX) { throw new NumberFormatException("radix " + radix + " less than Character.MIN_RADIX"); } if (radix > Character.MAX_RADIX) { throw new NumberFormatException("radix " + radix + " greater than Character.MAX_RADIX"); } int result = 0; boolean negative = false; int i = 0, len = s.length(); int limit = -Integer.MAX_VALUE; int multmin; int digit; if (len > 0) { char firstChar = s.charAt(0); if (firstChar < '0') { // Possible leading "+" or "-" if (firstChar == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (firstChar != '+') throw NumberFormatException.forInputString(s); if (len == 1) // Cannot have lone "+" or "-" throw NumberFormatException.forInputString(s); i++; } multmin = limit / radix; while (i < len) { // Accumulating negatively avoids surprises near MAX_VALUE digit = Character.digit(s.charAt(i++),radix); if (digit < 0) { throw NumberFormatException.forInputString(s); } if (result < multmin) { throw NumberFormatException.forInputString(s); } result *= radix; if (result < limit + digit) { throw NumberFormatException.forInputString(s); } result -= digit; } } else { throw NumberFormatException.forInputString(s); } return negative ? result : -result; }
字符串转int类型底层代码实现
private static int demo5(String numStr, int radix) { //获得字符串里面每个字符数据 Objects.requireNonNull(numStr); //获得字符串的长度 int length = numStr.length(); if (length == 0) { throw new NumberFormatException("字符串长度为0,无法解析!"); } int index = 0; int result = 0; boolean flag = false; //第一个字符 char firstChar = numStr.charAt(0);//获得字符串指定索引的字符数据 if (firstChar == '-') { flag = true; index++; } else if (firstChar == '+') { index++; } else if (firstChar < 48 || firstChar > 57) { throw new NumberFormatException("字符串里面包含非数字的数据"); } while (index < length) { char ch = numStr.charAt(index++);//字符数据 48-57 if (ch < 48 || ch > 57) { throw new NumberFormatException("字符串里面包含非数字的数据"); } int num = ch - 48; result = result * radix + num; } return flag ? -result : result; }
String numStr=“abcd”;
char ch = numStr.charAt(index++);转载地址:http://iknwi.baihongyu.com/