如何不采用java的內(nèi)置函數(shù)悠反,把String類(lèi)型轉(zhuǎn)換為int類(lèi)型残黑,想到兩種方法,如下代碼自己測(cè)試下
package com.journey.test;
public class AtoiTest {
public static void main(String[] args) throws Exception {
String s = "-2233113789";
System.out.println("轉(zhuǎn)換前的字符串: " + s);
System.out.println("atoi1轉(zhuǎn)換后的字符串:" + atoi1(s));
System.out.println("atoi2轉(zhuǎn)換后的字符串:" + atoi2(s));
}
方法一:遍歷檢索法斋否,遍歷字符串梨水,charAt() 方法用于返回指定索引處的字符,取出字符對(duì)照0-9的數(shù)字茵臭。
/**
* 不用java內(nèi)置函數(shù)疫诽,將String字符串轉(zhuǎn)換為數(shù)字
* @param s
* @return
* @throws Exception
*/
public static int atoi1(String s) throws Exception {
if (s == null || s.length() == 0) {
throw new Exception("要轉(zhuǎn)換的字符串為空,無(wú)法轉(zhuǎn)換旦委!");
}
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("要轉(zhuǎn)換的字符串格式錯(cuò)誤奇徒,無(wú)法轉(zhuǎn)換!");
}
}
for (int i = 0; i < num.length; i++) {
if (num[i] < 0 && i > 0) {
throw new Exception("要轉(zhuǎn)換的字符串格式錯(cuò)誤缨硝,無(wú)法轉(zhuǎn)換摩钙!");
}
if (num[i] < 0) {
continue;
}
retInt += Math.pow(10, num.length - i - 1) * num[i];
}
if (num[0] == -1) {//代表負(fù)數(shù)
retInt = -retInt;
}
return retInt;
}
方法二:判斷字符是否在 范圍 s.charAt(i)>'9' || s.charAt(i)<'0'
/**
* 不用java內(nèi)置函數(shù),將String字符串轉(zhuǎn)換為數(shù)字
* @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("要轉(zhuǎn)換的字符串為空查辩,轉(zhuǎn)換失斚俾伞奕短!");
}
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("要轉(zhuǎn)換的字符串格式錯(cuò)誤,轉(zhuǎn)換失斣染翎碑!");
}
}
retInt *=10;
retInt += s.charAt(i) - '0';
}
return isNegative ? -retInt : retInt;
}
}