利用好ascii的知识和substring用法就够
public class Solution {
public int StrToInt(String str) {
str.trim();
if(str.equals("")){
return 0;
}
for(int i=0;i<str.length();i++){
if(str.charAt(i)>'9'||str.charAt(i)<'0'){
if(!(i==0&&(str.charAt(i)=='-'||str.charAt(i)=='+')))
return 0; //如果遇到了不是数字的,还要判断是不是首个字母为符号
}
}
int t=1; //t表示正负号
if(str.charAt(0)=='-'||str.charAt(0)=='+'){
if(str.charAt(0)=='-')
t=-1; //记录正负号
str=str.substring(1);
}
int res=0;
for(int i=0;i<str.length();i++){
int temp=str.charAt(i)-'0';
res=res*10+temp;
}
return t*res;
}
}