8. String to Integer (atoi)

public class String_to_Integer {
    public static  int myAtoi(String str) {
        str=str.trim();
        int target=0;
        if(str.length()==0){
            return 0;
        }
        if(str.equals("+") || str.equals("-")){
            return 0;
        }

       for(int i=0;i<str.length();i++){
           char c=str.charAt(i);
           if(c=='+'||c=='-'){
               if(i==0){
                   continue;
               }
               str=str.substring(0,i);
               break;
           }
           if(!Character.isDigit(c)){
               if(i==0){
                   return 0;
               }
               str=str.substring(0,i);
               break;
           }
       }
        //System.out.println(str);
        if(str.equals("+") || str.equals("-")){
            return 0;
        }

        try {
            target=Integer.parseInt(str);
        }
        catch(Exception e) {
            if (str.charAt(0) == '-'){
                target = Integer.MIN_VALUE;
            } else {
                target = Integer.MAX_VALUE;
            }
        }
       return  target;
    }

    public static void main(String[] args) {

        System.out.println(myAtoi( "+22-"));

    }
}
原文地址:https://www.cnblogs.com/cstxx77/p/13056143.html