1. 程式人生 > >java 實現string 轉integer

java 實現string 轉integer

public int myParseToInt(String strInt) {
int result = 0;
for (int i = 0; i < strInt.length(); i++) {
if (strInt.charAt(i) >= '0' && strInt.charAt(i) <= '9') {
if (result == 0) {
result = strInt.charAt(i) - '0';
} else if (result == -2) {
result = -(strInt.charAt(i) - '0');

else {
result = (result>0?result* 10 + (strInt.charAt(i) - '0'):-(-result * 10 + (strInt.charAt(i) - '0')));
}
continue;
}
if (((strInt.charAt(i) > 0x08 && strInt.charAt(i) < 0x0E) || strInt
.charAt(i) == 0x20) && (result == 0))
continue;// 剪掉空白字元
if (strInt.charAt(i) == '+' && (result == 0)) {
result = 0;
continue;
}// 正數符號
if (strInt.charAt(i) == '-' && (result == 0)) {
result = -2;
continue;
}// 負數符號
if ((result == 0) || (result == -2))
result = 0;// 失敗返回0值
break;
}


return result;
}