
public int StrToInt(String str) {
//字符串为空
if (str == null||str.length() == 0) {
return 0;
}
//字符串只包含+或者-
if ("+".equals(str)||"-".equals(str)) {
return 0;
}
//判断如果字符串开头是+或者-,就需要进行符号处理
if (str.charAt(0) == '+'||str.charAt(0) == '-') {
char x = str.charAt(0);;
str = str.substring(1,str.length());
//注意正则表达式写法,这里意思就是判断字符串是否只包含数字
if (str.matches("^[0-9]*$")) {
int a = Integer.parseInt(str);
//判断是否在整数范围内
if (a>=Integer.MIN_VALUE&&a<=Integer.MAX_VALUE) {
if (x == '+') {
return a;
}else {
//如果是负数需要加-号
String s = "-"+a;
int b = Integer.parseInt(s);
return b;
}
}else {
return 0;
}
}
}else {
//这种是没有+或者-号的情况,默认就是正数,直接判断
if (str.matches("^[0-9]*$")) {
int a = Integer.parseInt(str);
if (a>=Integer.MIN_VALUE&&a<=Integer.MAX_VALUE) {
return a;
}else {
return 0;
}
}
}
return 0;
}
本文介绍了一种Java方法,用于将字符串转换为整数。该方法首先检查字符串的有效性,然后处理可能存在的正负号,并确保转换后的整数在有效范围内。通过使用正则表达式和Integer类的方法,实现了这一功能。
1876

被折叠的 条评论
为什么被折叠?



