Subject description:
A string into an integer, functional Integer.valueOf (String), and if the character string does not satisfy the requirement for, such as letters, or other form character string is not a number, 0 is output string appears.
For example: +123456 Output: 123456
123a outputs: 0
Analysis of ideas:
This question is mainly consider the special case character string processing, such as the input string is "", in this form, or the first character of the string is "+" and "-" character.
Code:
public class Test{
public int stringToInteger(String s){
if(s==null||s.length()==0)
return 0;
if(s.trim().equals("")) //如果输入的字符串为“ ”
return 0;
boolean flag=true; //用来判断数字的正负
if(s.charAt(0)=='-')
flag=false;
int sum=0;
for(int i=(s.charAt(0)=='+'||s.charAt(0)=='-')?1:0;i<s.length();i++){ //如果字符串的第一个字符是正负号,那么我们从第二个元素开始遍历,如果不是就从第一个元素遍历。
if(s.charAt(i)>'0'&&s.charAt(i)<'9'){
sum=sum*10+(s.charAt(i)-'0');
}else{
return 0;
}
}
if(flag==true)
return sum;
else
return -sum;
}
}