如何不采用java的内置函数,把String类型转换为int类型,想到两种方法,如下代码自己测试下
package com.journey.test;
public class AtoiTest {
public static void main(String[] args) throws Exception {
String s = "-2233113789";
System.out.println("转换前的字符串: " + s);
System.out.println("atoi1转换后的字符串:" + atoi1(s));
System.out.println("atoi2转换后的字符串:" + atoi2(s));
}
方法一:遍历检索法,遍历字符串,charAt() 方法用于返回指定索引处的字符,取出字符对照0-9的数字。
/**
* 不用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;
}
方法二:判断字符是否在 范围 s.charAt(i)>'9' || s.charAt(i)<'0'
/**
* 不用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;
}
}