Java Integer.parseInt(string) 实际上是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1410555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:46:45  来源:igfitidea点击:

How does Integer.parseInt(string) actually work?

javastringparsing

提问by Karl

Was asked this question recently and did not know the answer. From a high level can someone explain how Java takes a character / String and convert it into an int.

最近被问到这个问题,不知道答案。有人可以从高层次解释 Java 如何获取字符/字符串并将其转换为 int。

Many thanks

非常感谢

Karl

卡尔

Edit: Would also be good to know if other languages do a similar sort of thing as well.

编辑:也很高兴知道其他语言是否也做类似的事情。

采纳答案by rslite

Usually this is done like this:

通常这是这样做的:

  • init result with 0
  • for each character in string do this
    • result = result * 10
    • get the digit from the character ('0' is 48 ASCII (or 0x30), so just subtract that from the character ASCII code to get the digit)
    • add the digit to the result
  • return result
  • 初始化结果为 0
  • 对字符串中的每个字符执行此操作
    • 结果 = 结果 * 10
    • 从字符中获取数字('0' 是 48 ASCII(或 0x30),因此只需从字符 ASCII 代码中减去它即可获得数字)
    • 将数字添加到结果中
  • 返回结果

Edit: This works for any base if you replace 10 with the correct base and adjust the obtaining of the digit from the corresponding character (should work as is for bases lower than 10, but would need a little adjusting for higher bases - like hexadecimal - since letters are separated from numbers by 7 characters).

编辑:这适用于任何基数,如果你用正确的基数替换 10 并调整从相应字符中获取数字(应该对低于 10 的基数工作,但需要对更高的基数进行一些调整 - 如十六进制 -因为字母与数字用 7 个字符分隔)。

Edit 2: Char to digit value conversion: characters '0' to '9' have ASCII values 48 to 57 (0x30 to 0x39 in hexa), so in order to convert a character to its digit value a simple subtraction is needed. Usually it's done like this (where ord is the function that gives the ASCII code of the character):

编辑 2:字符到数字值的转换:字符“0”到“9”的 ASCII 值为 48 到 57(六进制中为 0x30 到 0x39),因此为了将字符转换为其数字值,需要进行简单的减法。通常是这样完成的(其中 ord 是给出字符 ASCII 码的函数):

digit = ord(char) - ord('0')

For higher number bases the letters are used as 'digits' (A-F in hexa), but letters start from 65 (0x41 hexa) which means there's a gap that we have to account for:

对于更高的数字基数,字母用作“数字”(六进制中的 AF),但字母从 65(0x41 六进制)开始,这意味着我们必须考虑一个差距:

digit = ord(char) - ord('0')
if digit > 9 then digit -= 7

Example: 'B' is 66, so ord('B') - ord('0') = 18. Since 18 is larger than 9 we subtract 7 and the end result will be 11 - the value of the 'digit' B.

示例:'B' 是 66,所以 ord('B') - ord('0') = 18。由于 18 大于 9,我们减去 7,最终结果将是 11 - 'digit' B 的值.

One more thing to note here - this works only for uppercase letters, so the number must be first converted to uppercase.

这里要注意的另一件事 - 这仅适用于大写字母,因此必须先将数字转换为大写。

回答by KLE

I'm not sure what you're looking for, as "high level". I'll give it a try:

我不确定你在找什么,作为“高水平”。我试试看:

  • take the String, parse all characters one by one
  • start with a total of 0
  • if it is between 0 and 9, total = (total x 10) + current
  • when done, the total is the result
  • 取字符串,一一解析所有字符
  • 从一共 0 开始
  • 如果它在 0 到 9 之间, total = (total x 10) + current
  • 完成后,总数就是结果

回答by Michael Borgwardt

The source code of the Java API is freely available. Here's the parseInt() method. It's rather long because it has to handle a lot of exceptional and corner cases.

Java API 的源代码是免费提供的。这是 parseInt() 方法。它相当长,因为它必须处理许多特殊和极端情况。

public static int parseInt(String s, int radix)
    throws NumberFormatException
{
    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, max = s.length();
int limit;
int multmin;
int digit;

if (max > 0) {
    if (s.charAt(0) == '-') {
    negative = true;
    limit = Integer.MIN_VALUE;
    i++;
    } else {
    limit = -Integer.MAX_VALUE;
    }
    multmin = limit / radix;
    if (i < max) {
    digit = Character.digit(s.charAt(i++),radix);
    if (digit < 0) {
        throw NumberFormatException.forInputString(s);
    } else {
        result = -digit;
    }
    }
    while (i < max) {
    // 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);
}
if (negative) {
    if (i > 1) {
    return result;
    } else {    /* Only got "-" */
    throw NumberFormatException.forInputString(s);
    }
} else {
    return -result;
}
}

回答by zkarthik

  • Find the length of the String (s) (say maxSize )
  • Initialize result = 0
  • begin loop ( int j=maxSize, i =0 ; j > 0; j--, i++)
  • int digit = Character.digit(s.charAt(i))
  • result= result + digit * (10 power j-1)
  • end loop
  • return result
  • 找到字符串的长度(s)(比如 maxSize )
  • 初始化 result = 0
  • 开始循环 ( int j=maxSize, i =0 ; j > 0; j--, i++)
  • int digit = Character.digit(s.charAt(i))
  • result= result + digit * (10 power j-1)
  • 结束循环
  • 返回结果

回答by javaMan

public class StringToInt {

    public int ConvertStringToInt(String s) throws NumberFormatException
    {
        int num =0;
        for(int i =0; i<s.length();i++)
        {
            if(((int)s.charAt(i)>=48)&&((int)s.charAt(i)<=59))
            {
                num = num*10+ ((int)s.charAt(i)-48);
            }
            else
            {
                throw new NumberFormatException();
            }

        }
        return num; 
    }

    public static void main(String[]args)
    {
        StringToInt obj = new StringToInt();
        int i = obj.ConvertStringToInt("1234123");
        System.out.println(i);
    }

}

回答by Basheer AL-MOMANI

this is my simple implementation of parse int

这是我的简单实现 parse int

public static int parseInteger(String stringNumber) {
    int sum=0;
    int position=1;
    for (int i = stringNumber.length()-1; i >= 0 ; i--) {
       int number=stringNumber.charAt(i) - '0';
       sum+=number*position;
       position=position*10;

    }
    return sum;
}

回答by Shishir Shetty

Here is what I came up with (Note: No checks are done for alphabets)

这是我想出的(注意:不检查字母)

int convertStringtoInt(String number){

    int total =0;
    double multiplier = Math.pow(10, number.length()-1);
        for(int i=0;i<number.length();i++){

            total = total + (int)multiplier*((int)number.charAt(i) -48);
            multiplier/=10;

        }

        return total;
    }