天天看點

java string類型轉換成int類型(string怎麼強轉int)

大家好,又見面了,我是你們的朋友全棧君。

1.問題思考:

需要明确的是String是引用類型,int是基本類型,是以兩者的轉換并不是基本類型間的轉換,這也是該問題提出的意義所在,SUN公司提供了相應的類庫供程式設計人員直接使用。

2.Integer.parseInt(str) 與 Integer.valueOf(Str).intValue() :

其實檢視Java源碼不難發現後者的實作是基于parseInt函數來實作的,是以很有必要分析parseInt源碼。

3.Integer.parseInt(str) 源碼分析:

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.
         */

        if (s == null) {
            throw new NumberFormatException("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;
        int i = 0, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);

                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);
                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;
    }           

複制

加紅源碼如下:

public static int digit(char ch, int radix) {
        return digit((int)ch, radix);
    }           

複制

/* @param   codePoint the character (Unicode code point) to be converted.
     * @param   radix   the radix.
     * @return  the numeric value represented by the character in the
     *          specified radix.
     * @see     Character#forDigit(int, int)
     * @see     Character#isDigit(int)
     * @since   1.5
     */
    public static int digit(int codePoint, int radix) {
        return CharacterData.of(codePoint).digit(codePoint, radix);
    }           

複制

可以看出加紅代碼是将字元 => Unicode(字元統一編碼) => Unicode(數字統一編碼) => 數字。

從上面的分析可以發現源碼是取出字元串中的每個字元,然後将字元轉換為數字進行拼接,但是在拼接的過程中SUN公司的程式設計人員是将其先拼接為負數,再用三元運算轉換選擇輸出。自己并不認同,因為這樣的做法是不利于了解,當然作者可能有自己的考慮,值得揣摩。

4.自己動手,豐衣足食:

思路:

化整為零 -> 将引用類型的String分解為char;

逐個擊破 -> 進本資料類型之間的轉換Character.digit(ch,radix) / Character.getNumericValue(ch) 原理相同;

由點及線-> 将數字放到不同權值得相應位置上,組成int型數值。

注:

正負号判斷,數值長度判斷,數字合法性校驗(0-9)…

CODEING:

public static int change(String s){
		int result = 0;     //數值
		int len = s.length(); 
		int indexEnd = len - 1;             //控制由右及左取字元(數字)
		int indexBegin = 0;     //起始位置(存在+ - 号)
		boolean negative = false;     //确定起始位置及輸出結果标志符
		int position = 1;                   //權值:起始位置為個位
		int digit = 0;     //數字
		
	if(len > 0){
	    char firstChar = s.charAt(0);
            if (firstChar < '0') { 
                if (firstChar == '-') {
                    negative = true;
                    indexBegin = 1;
                }else if(firstChar == '+'){
                	indexBegin = 1;
                }else if (firstChar != '+'){
                	throw new NumberFormatException(s);
                } 
                if (len == 1) throw new NumberFormatException(s);
            }
            
            while (indexEnd >= indexBegin) {
            	//(int) s.charAt(indexEnd--);隻是該字元的數字編碼,十進制數字的Unicode碼範圍為48-57
            	if(s.charAt(indexEnd) < 48 || s.charAt(indexEnd)> 57){
            		throw new NumberFormatException(s);
            	}
                //int temp = Character.getNumericValue(s.charAt(indexEnd--));
                int temp = Character.digit(s.charAt(indexEnd--), 10);
                digit = temp * position;
                result += digit;
                position *= 10;
            }
		}
		return negative ? -result : result;
	}           

複制

5.C++的寫法:

handle four cases: – discards all leading whitespaces;- sign of the number;- overflow;- invalid input

int atoi(const char *str) {    int sign = 1, base = 0, i = 0;    while (str[i] == ' ') { i++; }    if (str[i] == '-' || str[i] == '+') {        sign = 1 - 2 * (str[i++] == '-'); //神一般的寫法 或者 凡人 sign = str.charAt(i++) == '-' ? -1 : 1;    }    while (str[i] >= '0' && str[i] <= '9') {        if (base >  INT_MAX / 10 || (base == INT_MAX / 10 && str[i] - '0' > 7)) {            if (sign == 1) return INT_MAX;            else return INT_MIN;        }        base  = 10 * base + (str[i++] - '0');    }    return base * sign;}           

複制

6.學無止境,Java更新版:

public static int myAtoi(String str) {
	    int index = 0, sign = 1, total = 0;
	    //1. Empty string
	    if(str.length() == 0) return 0;

	    //2. Remove Spaces
	    while(str.charAt(index) == ' ' && index < str.length()) // str = str.trim();
	        index ++;

	    //3. Handle signs
	    if(str.charAt(index) == '+' || str.charAt(index) == '-'){
	        sign = str.charAt(index) == '+' ? 1 : -1;
	        index ++;
	    }
	    
	    //4. Convert number and avoid overflow
	    while(index < str.length()){
	        int digit = str.charAt(index) - '0';
	        if(digit < 0 || digit > 9) break;

	        //check if total will be overflow after 10 times and add digit
	        if(Integer.MAX_VALUE/10 < total || Integer.MAX_VALUE/10 == total && Integer.MAX_VALUE %10 < digit)
	            return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;

	        total = 10 * total + digit;
	        index ++;
	    }
	    return total * sign;
	}           

複制

釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/128955.html原文連結:https://javaforall.cn