字符串转化为整数
public class Main4 {
public static int StrToInt(String str){
if(str.length()==0){
return 0;
}
char[] chars = str.toCharArray();
int flag=0;
if(chars[0]=='+')
flag=1;
else if(chars[0]=='-')
flag=2;
int satrt=flag>0?1:0;
int res=0;
for (int i = satrt; i <chars.length ; i++) {
if(Character.isDigit(chars[i])){
int temp = chars[i] - '0';
res=res*10+temp;
}else {
return 0;
}
}
return flag!=2?res:-res;
}
public static void main(String[] args) {
String s="-12312312";
System.out.println("使用库函数转换:"+Integer.valueOf(s));
int res = Main4.StrToInt(s);
System.out.println("使用自己的函数转换:"+res);
}
}
主要是这一句实现转换 int temp = chars[i] - ‘0’;