【问题标题】:How does Integer.parseInt(string) actually work?Integer.parseInt(string) 实际上是如何工作的?
【发布时间】:2010-11-27 11:43:58
【问题描述】:

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

【问题讨论】:

  • 您可以打开src.zip 并亲自查看(针对一种特定实现)。
  • 我已经用一个关于减码的例子更新了答案

标签: java string parsing


【解决方案1】:

这是我的新方法,不是数学方法。

let n = 12.277;
// converting  to string
n = n.toString();

let int = "";

for (let i = 0; i < n.length; i++) {

    if (n[i] != ".") {
        int += n[i];
    } else {
        break;
    }
}

console.log(Number(int));

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 人们不只看源头,这仍然让我感到惊讶。下载 JDK 源并将其连接到 IDE 中的源查找应该是您在设置新工作站时首先要做的事情之一...
    【解决方案3】:
    • 求字符串的长度(s)(比如 maxSize )
    • 初始化result = 0
    • 开始循环( int j=maxSize, i =0 ; j &gt; 0; j--, i++)
    • int digit = Character.digit(s.charAt(i))
    • result= result + digit * (10 power j-1)
    • 结束循环
    • 返回结果

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        【解决方案5】:

        这是我对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;
        }
        

        【讨论】:

          【解决方案6】:
          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);
              }
          
          }
          

          【讨论】:

            【解决方案7】:

            通常是这样完成的:

            • 初始化结果为 0
            • 对字符串中的每个字符执行此操作
              • 结果 = 结果 * 10
              • 从字符中获取数字('0' 是 48 ASCII(或 0x30),因此只需从字符 ASCII 码中减去它即可得到数字)
              • 将数字添加到结果中
            • 返回结果

            编辑:如果您将 10 替换为正确的基数并调整从相应字符获取数字的方式,这适用于任何基数(对于低于 10 的基数应该正常工作,但需要稍加调整以适应更高的基数 - 例如十六进制 - 因为字母与数字相隔 7 个字符)。

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

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

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

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

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

            这里还有一点需要注意 - 这仅适用于大写字母,因此必须先将数字转换为大写。

            【讨论】:

            • 您能否扩展您的第 4 点:那么它只是减去 ascii 代码的情况吗?
            • +1 提供了一个很好的“高级”解释,因为海报特别要求(而不是低级源代码)。
            • 很好,简单但很好的解释。
            【解决方案8】:

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

            • 取String,一一解析所有字符
            • 从0开始
            • 如果在0到9之间,total = (total x 10) + current
            • 完成后,总和就是结果

            【讨论】:

              猜你喜欢
              • 2021-01-21
              • 2011-09-27
              • 2021-12-16
              • 2013-03-14
              • 2021-03-23
              • 2011-02-11
              • 2017-07-31
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多