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;
}
剑指offer之把字符串转换成整数
猜你喜欢
转载自blog.csdn.net/AIJXB/article/details/113500071
今日推荐
周排行