Java 取字串中第一組數值
第一個字元為非數字時返回負值;
public static int myAtoi(String str) {
str = str.trim();
boolean flag = false;
long result = 0;
int start = -1;
int end = -1;
//int symbol = 1;
if(str.length() > 0){
char[] arr = str.toCharArray();
for(int i = 0; i < arr.length ; i++){
if(arr[i] >= 48 && arr[i] <= 57){
//if(i == 0 && arr[i] == 48)symbol *= 1;
if(start == -1){
start = i;
flag = true;
}
else if(start != -1){
end = i;
}
}
else if(start == -1){
//if(i == 0)symbol *= -1;
}
else if(i == 0 && arr[i] != 48){
//symbol *= -1;
}
else if(i != 0 && start != -1){
break;
}
}
}
try {
result = start >= 0 && start < end ? /*symbol**/Long.parseLong(str.substring(start, end+1)) : result;
result = result > Integer.MAX_VALUE ? Integer.MAX_VALUE : result < Integer.MIN_VALUE ? Integer.MIN_VALUE : result;
} catch (NumberFormatException e) {
e.printStackTrace();
}
return flag ? (int)result : 0;
}