不使用java内置函数,将String字符串转换为int类型
package com.test; public class AtoiTest { public static void main(String[] args) throws Exception { String s = "-011134"; System.out.println("转换前的字符串:" + s); System.out.println("atoi1转换后的字符串:" + atoi1(s)); System.out.println("atoi2转换后的字符串:" + atoi2(s)); } /** * 不用java内置函数,将String字符串转换为数字 * @param s * @return * @throws Exception */ public static int atoi1(String s) throws Exception { if (s == null || s.length() == 0) { throw new Exception("要转换的字符串为空,无法转换!"); } int retInt = 0; int[] num = new int[s.length()]; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); switch (c) { case '-': num[i] = -1; break; case '0': num[i] = 0; break; case '1': num[i] = 1; break; case '2': num[i] = 2; break; case '3': num[i] = 3; break; case '4': num[i] = 4; break; case '5': num[i] = 5; break; case '6': num[i] = 6; break; case '7': num[i] = 7; break; case '8': num[i] = 8; break; case '9': num[i] = 9; break; default: throw new Exception("要转换的字符串格式错误,无法转换!"); } } for (int i = 0; i < num.length; i++) { if (num[i] < 0 && i > 0) { throw new Exception("要转换的字符串格式错误,无法转换!"); } if (num[i] < 0) { continue; } retInt += Math.pow(10, num.length - i - 1) * num[i]; } if (num[0] == -1) {//代表负数 retInt = -retInt; } return retInt; } /** * 不用java内置函数,将String字符串转换为数字 * @param s * @return * @throws Exception */ public static int atoi2(String s) throws Exception{ int retInt = 0; if (s == null || s.length() == 0) { throw new Exception("要转换的字符串为空,无法转换!"); } boolean isNegative = false; for (int i = 0; i < s.length(); i++) { if (i==0) { if(s.charAt(i)=='-'){ isNegative = true; continue; } }else{ if(s.charAt(i)>'9' || s.charAt(i)<'0'){ throw new Exception("要转换的字符串格式错误,无法转换!"); } } retInt *=10; retInt += s.charAt(i) - '0'; } return isNegative ? -retInt : retInt; } }