示例代码:
public static int StrToInt(String s) {
// 空串
if (s.isEmpty()) {
return 0;
}
// 去前后空格就什么都没了
String str = s.trim();
if (str.isEmpty()) {
return 0;
}
int len = 0;
// 定义符号
String rex = "";
if ((str.charAt(0) == '+' || str.charAt(0) == '-') && str.length() > 1) {
rex = str.substring(0, 1);
str = str.substring(1);
while (str.charAt(len) >= 48 && str.charAt(len) <= 57) {
len++;
// 防止str.charAt(len)报错
if (len == str.length()) {
break;
}
}
if (!(str.charAt(0) >= 48 && str.charAt(0) <= 57)) {
return 0;
}
} else if (str.charAt(0) >= 48 && str.charAt(0) <= 57) {
while (str.charAt(len) >= 48 && str.charAt(len) <= 57) {
len++;
if (len == str.length()) {
break;
}
}
} else {
return 0;
}
String numStr = str.substring(0, len);
// 这里为了防止得出的数字超出范围而报错,我们采用Long类型来获取num值
if (numStr.length() > 18) {
numStr = numStr.substring(0, 15);
}
// 添加上符号
long res = Long.parseLong(rex + numStr);
if (res > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (res < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return ((int) res);
}