如果字符串存在,则考虑第一个字符为+、第一个字符为-、存在不合法字符三种特殊情况
public class Solution {
public int StrToInt(String str) {
//首先将字符串转为数组
char[] ch = str.toCharArray();
if(ch == null || ch.length ==0) return 0;//判断ch为空和长度为0的情况
int flg = 1;
if(ch[0] == '-'){
flg = -1;
ch[0] ='0';
}else if(ch[0] == '+'){
flg = 1;
ch[0] = '0';//注意字符与字符比较,右边要为字符,0字符表示'0'
}
int sum = 0;
for(int i = 0;i < str.length();i++){
if(ch[i] < '0' || ch[i] > '9'){
sum = 0;
break;
}
sum = sum*10 + ch[i] -'0';//状态初始式
}
return flg*sum;
}
}