Java中string 轉換成 integer的方式及原理

1 Integer.parseInt(String str)方法

public static int parseInt(String s) throws NumberFormatException {
        //內部默認調用parseInt(String s, int radix)基數設置爲10
        return parseInt(s,10);
    }

2 Integer.parseInt(String s, int radix)方法

public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        /*
         * WARNING: This method may be invoked early during VM initialization
         * before IntegerCache is initialized. Care must be taken to not use
         * the valueOf method.
         */
        //判斷字符是否爲null
        if (s == null) {
            throw new NumberFormatException("s == null");
        }
        //基數是否小於最小基數
        if (radix < Character.MIN_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " less than Character.MIN_RADIX");
        }
        //基數是否大於最大基數
        if (radix > Character.MAX_RADIX) {
            throw new NumberFormatException("radix " + radix +
                                            " greater than Character.MAX_RADIX");
        }

        int result = 0;
        //是否時負數
        boolean negative = false;
        //char字符數組下標和長度
        int i = 0, len = s.length();
        //限制
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;
        //判斷字符長度是否大於0,否則拋出異常
        if (len > 0) {
            //第一個字符是否是符號
            char firstChar = s.charAt(0);
            //根據ascii碼錶看出加號(43)和負號(45)對應的
            //十進制數小於‘0’(48)的
            if (firstChar < '0') { // Possible leading "+" or "-"
                //是負號
                if (firstChar == '-') {
                    //負號屬性設置爲true
                    negative = true;
                    limit = Integer.MIN_VALUE;
                }
                //不是負號也不是加號則拋出異常
                else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);
                //如果有符號(加號或者減號)且字符串長度爲1,則拋出異常
                if (len == 1) // Cannot have lone "+" or "-"
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // Accumulating negatively avoids surprises near MAX_VALUE
                //返回指定基數中字符表示的數值。(此處是十進制數值)
                digit = Character.digit(s.charAt(i++),radix);
                //小於0,則爲非radix進制數
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                //這裏是爲了保證下面計算不會超出最大值
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        //根據上面得到的是否負數,返回相應的值
        return negative ? result : -result;
    }

3 Character.digit(char ch, int radix)方法

返回指定基數中字符表示的數值。

public static int digit(int codePoint, int radix) {
        //基數必須再最大和最小基數之間
        if (radix < MIN_RADIX || radix > MAX_RADIX) {
            return -1;
        }
        
        if (codePoint < 128) {
            // Optimized for ASCII
            int result = -1;
            //字符在0-9字符之間
            if ('0' <= codePoint && codePoint <= '9') {
                result = codePoint - '0';
            }
            //字符在a-z之間
            else if ('a' <= codePoint && codePoint <= 'z') {
                result = 10 + (codePoint - 'a');
            }
            //字符在A-Z之間
            else if ('A' <= codePoint && codePoint <= 'Z') {
                result = 10 + (codePoint - 'A');
            }
            //通過判斷result和基數大小,輸出對應值
            //通過我們parseInt對應的基數值爲10,
            //所以,只能在第一個判斷(字符在0-9字符之間)
            //中得到result值 否則後續程序會拋出異常
            return result < radix ? result : -1;
        }
        return digitImpl(codePoint, radix);
    }

4 總結

  1. parseInt(String s)--內部調用parseInt(s,10)(默認爲10進制)
  2. 正常判斷null,進制範圍,length等
  3. 判斷第一個字符是否是符號位
  4. 循環遍歷確定每個字符的十進制值
  5. 通過*= 和-= 進行計算拼接
  6. 判斷是否爲負值 返回結果。

java int怎麼轉換爲string

1.兩種方法,一個是再int後面+“”,就可以轉爲字符串。

另一個,

nt i=12345;
String s="";
第一種方法:s=i+"";
第二種方法:s=String.valueOf(i);
這兩種方法有什麼區別呢?作用是不是一樣的呢?是不是在任何下都能互換呢?

String -> int

s="12345";
int i;
第一種方法:i=Integer.parseInt(s);
第二種方法:i=Integer.valueOf(s).intValue();
這兩種方法有什麼區別呢?作用是不是一樣的呢?是不是在任何下都能互換呢?

以下是答案:

第一種方法:s=i+"";   //會產生兩個String對象
第二種方法:s=String.valueOf(i); //直接使用String類的靜態方法,只產生一個對象

第一種方法:i=Integer.parseInt(s);//直接使用靜態方法,不會產生多餘的對象,但會拋出異常
第二種方法:i=Integer.valueOf(s).intValue();//Integer.valueOf(s) 相當於 new Integer(Integer.parseInt(s)),也會拋異常,但會多產生一個對象

--------------------------------------------------------------------

1如何將字串 String 轉換成整數 int?

A. 有兩個方法:

1). int i = Integer.parseInt([String]); 或
i = Integer.parseInt([String],[int radix]);

2). int i = Integer.valueOf(my_str).intValue();

注: 字串轉成 Double, Float, Long 的方法大同小異.

2 如何將整數 int 轉換成字串 String ?

A. 有叄種方法:

1.) String s = String.valueOf(i);

2.) String s = Integer.toString(i);

3.) String s = "" + i;

注: Double, Float, Long 轉成字串的方法大同小異.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章