Java implementation string conversion to Integer

Source: Internet
Author: User

1, ideas and points of attention reference: http://blog.sina.com.cn/s/blog_514c89a90100d7qh.html
There are a few things to summarize 1) The string begins with the "+" sign or the "-" number of the processing 2) of the illegal character's judgment (not the number) 3) integer overflow problem. Look at how the source code for Integer.parseint (String Sting) in the Java library handles these problems.
/** * Parses the specified string as a signed decimal integer value. The ASCII * character \u002d ('-') is recognized as the minus sign. * * @param String * The string representation of an integer value. * @return The primitive integer value represented by {@code string}. * @throws NumberFormatException * If {@code string} cannot is parsed as an integer value. */public static int parseint (string string) throws NumberFormatException {return parseint (string, ten);}/** * Parses t He specified string as a signed integer value using the specified * radix. The ASCII character \u002d ('-') is recognized as the minus sign. * * @param String * The string representation of an integer value. * @param radix * The radix to use when parsing. * @return The primitive integer value represented by {@code string} using * {@code radix}.            * @throws NumberFormatException * If {@code string} cannot is parsed as an integer value, * or {@code Radix < Character.min_radix | | * Radix > CHARACTER.MAX_RADIX}. */public static int parseint (string string, int radix) throws NumberFormatException {if (Radix < Character.min_radi X | |    Radix > Character.max_radix) {throw new NumberFormatException ("Invalid Radix:" + radix);    } if (string = = null) {throw invalidint (string);    } int length = String.Length (), i = 0;    if (length = = 0) {throw invalidint (string);    } Boolean negative = String.charat (i) = = '-';    if (negative && ++i = = length) {throw invalidint (string); } return Parse (string, I, radix, negative);}  private static int Parse (string string, int offset, int radix, Boolean negative) throws numberformatexception {int Max    = Integer.min_value/radix;    int result = 0, length = string.length ();        while (offset < length) {int digit = Character.digit (String.charat (offset++), radix); if (digit = =-1) {thRow Invalidint (string);        } if (Max > result) {throw invalidint (string);        } int next = result * RADIX-DIGIT;        if (Next > result) {throw invalidint (string);    } result = next;        } if (!negative) {result =-result;        if (Result < 0) {throw invalidint (string); }} return result;
parseint (String string, int radix) determines 1)Radix-in out of range ( Character.Min_radix =2,Character.Max_radix) =36)2) The string is null3) String length is empty4) The first bit of the string is "-" and only one bitdoes not have an exception afterParse (string string,intOffset,intRadix,Booleannegative)Judging, parameters are string, offset, binary,Negative(Offset=0,negative=false If there is no "-" at the beginning, otherwise offset=1,neagtive=true)in theParse (string string,intOffset,intRadix,Booleannegative) is primarily a judgment of overflow. Use offset++ to control the movement, in the while (Offset < length) loop until the countdown second place when, if alreadyless than max = Integer.min_value/radix indicates that it is bound to overflow. For example " -2147483648" at the bottom of the second place. : result=-214748364,max=-214748364,max>result not established indicates that the last one can be processed.       Why not get the current result first and then the integer.min_value comparison? Instead, start with < Span style= "Background-color:inherit" >integer.min_value/radix comparison to decide whether to add the next bit? Self - evident. 2, the reference source is realconvert string to Integeryou can compare http://zhedahht.blog.163.com/blog/static/25411174200731139971/.
public class Stringtointtest {/** * @author Cao Yanfong Peking University */public static void main (string[] args) {/            /TODO Auto-generated method stub try {System.out.println (parseint ("Cao21 ' 474fefda8364fe7"));            System.out.println (parseint ("-2147483648"));            System.out.println (parseint ("-2147483651"));            System.out.println (parseint ("-2147483648"));        System.out.println (parseint ("-21474836410"));        } catch (MyException e) {//TODO auto-generated catch block E.printstacktrace (); }} private static int parseint (string string) throws MyException {/* Exception Case 1: string is null */if (string        = = null) {throw new MyException ("string is null!");        } int length = String.Length (), offset = 0; /* Exception Condition 2: string length is 0 */if (length = = 0) {throw new MyException ("string length is 0!)        ");        } Boolean negative = String.charat (offset) = = '-'; /* Exception Case 3: The string is '-' */if (negative && ++offset = = length) {throw new MyException ("string: '-'!        ");        } int result = 0;        char[] temp = String.tochararray ();            while (offset < length) {char digit = temp[offset++];                if (digit <= ' 9 ' && digit >= ' 0 ') {int currentdigit = digit-' 0 ';                 /* Exception 4: Already equals INTEGER.MAX_VALUE/10, judging the last one to add: * If it is negative, the last one is 8 if it is positive, the last one is 7. */if (result = = INTEGER.MAX_VALUE/10) {if (negative = = False &AMP;&A mp Currentdigit > 7) | | (Negative && currentdigit > 8)) {throw new MyException ("Overflow!                    "); }/* Exception 5: Already greater than INTEGER.MAX_VALUE/10 * No matter what the last one is, it will exceed the integer.             Max_value */} else if (Result > Integer.max_value/10) {       throw new MyException ("Overflow!                ");                } int next = result * + currentdigit;            result = Next;        }} if (negative) {result =-result;    } return result; }}//Custom exception */class MyException extends Exception {/** * */private static final long Serialversionuid = 1    749149488419303367L;     String message;    Public myexception (String message) {//TODO auto-generated constructor stub this.message = message;    } @Override Public String getMessage () {//TODO auto-generated method stub return message; } }
**************************** "If it is negative, the last one is 8 if it is positive, the last one is 7" can be used integer.min_value%10 and integer.max_value%10 to beg.


Java implementation string conversion to Integer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.