【问题标题】:Manually converting a string to an integer in Java在 Java 中手动将字符串转换为整数
【发布时间】:2012-01-17 11:22:11
【问题描述】:

我的字符串由一系列数字组成(例如"1234")。如何在不使用Integer.parseInt 等Java 库函数的情况下将String 作为int 返回?

public class StringToInteger {
  public static void main(String [] args){
    int i = myStringToInteger("123");
    System.out.println("String decoded to number " + i);
  }

  public int myStringToInteger(String str){
      /* ... */
  }
}

【问题讨论】:

  • 如果您不想使用,请复制粘贴Integer.parseInt() 的代码。为什么会有这么荒谬的要求?
  • 哇。四个人在不到两分钟的时间内没有阅读问题就回答了。太棒了:)
  • @JB Nizet:正要对此进行评论(粘贴 parseInt 代码)。这可能是家庭作业......而“学习编程”从来都不是一个荒谬的要求:)
  • @JBNizet 可能是一个面试问题或家庭作业...

标签: java string integer


【解决方案1】:

这有什么问题?

int i = Integer.parseInt(str);

编辑:

如果您真的需要手动进行转换,试试这个:

public static int myStringToInteger(String str) {
    int answer = 0, factor = 1;
    for (int i = str.length()-1; i >= 0; i--) {
        answer += (str.charAt(i) - '0') * factor;
        factor *= 10;
    }
    return answer;
}

上述方法适用于正整数,如果数字为负数,您必须先进行一些检查,但我将把它作为练习留给读者。

【讨论】:

  • @Oscar.. 要求是,不应该使用任何包装类
  • 您不需要将字符串转换为 char 数组。请改用str.charAt
  • @dogbane 但是这样做每次都会调用一个方法,我更喜欢进行一次转换,然后直接访问数组
  • toCharArray 将整个字符串复制到一个 char 数组中,而 str.charAt 每次只访问底层的 char 数组索引。另外,看看:stackoverflow.com/questions/196830/…
  • @Manu 那些包装类在哪里?我在这个解决方案中看不到它们。
【解决方案2】:

如果不允许使用标准库,有很多方法可以解决这个问题。考虑这一点的一种方法是作为递归函数:

  1. 如果 n 小于 10,只需将其转换为包含其数字的单字符字符串。例如,3 变为“3”。
  2. 如果n大于10,则使用除法和取模得到n的最后一位以及排除最后一位形成的数字。递归获取第一个数字的字符串,然后为最后一个数字附加适当的字符。例如,如果 n 为 137,您将递归计算“13”并加上“7”得到“137”。

您需要对特殊情况 0 和负数进行逻辑处理,否则这可以相当简单地完成。

由于我怀疑这可能是家庭作业(并且知道在某些学校确实如此),因此我将把实际的转换作为练习留给读者。 :-)

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    在这种情况下使用 long 而不是 int。 您需要检查溢出。

    public static int StringtoNumber(String s) throws Exception{
        if (s == null || s.length() == 0)
            return 0;
        while(s.charAt(0) == ' '){
            s = s.substring(1);
        }
        boolean isNegative = s.charAt(0) == '-';
        if (s.charAt(0) == '-' || (s.charAt(0) == '+')){
            s = s.substring(1);
        }
    
        long result = 0l;
        for (int i = 0; i < s.length(); i++){
            int value = s.charAt(i) - '0';
            if (value >= 0 && value <= 9){
                if (!isNegative && 10 * result + value > Integer.MAX_VALUE ){
                    throw new Exception();
                }else if (isNegative && -1 * 10 * result - value < Integer.MIN_VALUE){
                    throw new Exception();
                }
                result = 10 * result + value;
            }else if (s.charAt(i) != ' '){
                return (int)result;
            }
        }
        return isNegative ? -1 * (int)result : (int)result;
    }
    

    【讨论】:

    • 您能解释一下为什么我们要扣除“0”来获得价值吗? int value = s.charAt(i) - '0'。我不明白这一行。
    • @Hengameh 字符 '0' 的 ASCII 值 = 48。如果您查看 ASCII 表,所有其他后续字符构成整数 (1,2,..9) 都有 ASCII 值以 1 为增量。在上面的代码中,user1559897 使用这个事实并获得绝对整数值作为字符 '0' 的 ascii 值的差。
    【解决方案4】:

    已在此处发布的答案的替代方法。可以从前面遍历字符串,建号

     public static void stringtoint(String s){      
        boolean isNegative=false;
        int number =0;      
        if (s.charAt(0)=='-') {
            isNegative=true;            
        }else{
            number = number* 10 + s.charAt(0)-'0';
        }
    
        for (int i = 1; i < s.length(); i++) {
    
            number = number*10 + s.charAt(i)-'0';           
        }
        if(isNegative){
            number = 0-number;
        }
        System.out.println(number);
    }
    

    【讨论】:

    • 您能解释一下为什么我们要扣除“0”来获得价值吗? s.charAt(i) - '0'。我不明白这一行。感谢分享代码。
    • 如果您打印 s.charAt(i) 它会打印字符的 ascii 代码。因此,为了得到实际数字,我们从字符串中的字符中减去 '0' 的 ascii 代码
    【解决方案5】:

    如果有正确的提示,我认为大多数受过高中教育的人都可以自己解决这个问题。大家都知道134 = 100x1 + 10x3 + 1x4

    大多数人错过的关键部分是,如果你在 Java 中做这样的事情

     System.out.println('0'*1);//48
    

    它将选择ascii chart字符 0 的十进制表示并将其乘以1。

    ascii table 中,字符 0 的十进制表示为 48。因此上面的行将打印 48。因此,如果您执行类似 '1'-'0' 的操作,则与 49-48 相同。由于在 ascii 图表中,字符 0-9 是连续的,因此您可以将 0 到 9 之间的任何字符减去 0 以获得其整数值。一旦你有了一个字符的整数值,那么将整个字符串转换为 int 就很简单了。

    这是解决问题的另一种方法

    String a = "-12512";
    char[] chars = a.toCharArray();
    boolean isNegative = (chars[0] == '-');
    if (isNegative) {
        chars[0] = '0';
    }
    
    int multiplier = 1;
    int total = 0;
    
    for (int i = chars.length - 1; i >= 0; i--) {
        total = total + ((chars[i] - '0') * multiplier);
        multiplier = multiplier * 10;
    }
    
    if (isNegative) {
        total = total * -1;
    }
    

    【讨论】:

      【解决方案6】:

      使用这个:

      static int parseInt(String str) {
          char[] ch = str.trim().toCharArray();
          int len = ch.length;
          int value = 0;
          for (int i=0, j=(len-1); i<len; i++,j--) {
              int c = ch[i];
              if (c < 48 || c > 57) {
                  throw new NumberFormatException("Not a number: "+str);
              }
              int n = c - 48;
              n *= Math.pow(10, j);
              value += n;
          }
          return value;
      }
      

      而且对了,你可以处理负整数的特殊情况,否则会抛出异常NumberFormatException

      【讨论】:

        【解决方案7】:

        您可以这样做:从字符串中,为每个元素创建一个字符数组,保存索引,并将其 ASCII 值乘以实际反向索引的幂。将部分因子相加即可得到。

        Math.pow 只需要少量转换(​​因为它返回一个双精度),但您可以通过创建自己的幂函数来避免它。

        public static int StringToInt(String str){
            int res = 0;
            char [] chars = str.toCharArray();
            System.out.println(str.length());
            for (int i = str.length()-1, j=0; i>=0; i--, j++){
                int temp = chars[j]-48;
                int power = (int) Math.pow(10, i);
                res += temp*power;
                System.out.println(res);
            }
            return res;
        }
        

        【讨论】:

        • 对不起,我没有看到下面的答案,我在吃午饭的时候把窗户一直开着,然后才真正发布:)
        • 这是什么意思? chars[j]-48。感谢分享代码。
        • 我的意思是已经发布了类似的解决方案,只是我没有注意到它:)
        • 其实我是在问这个问题:chars[j]-48。无论如何谢谢:)
        • ops :) 如果您使用 ASCII 表 asciitable.com,您会看到整数从索引 48 开始。由于我使用的是 ascii 值,因此我需要减去 48。请注意,有没有输入检查 - 如果没有数字,则转换错误
        【解决方案8】:

        使用 Java 8,您可以执行以下操作:

        public static int convert(String strNum)
        {
           int result =strNum.chars().reduce(0, (a, b)->10*a +b-'0');
        }
        
        1. 将 srtNum 转换为 char
        2. 对于每个字符(表示为'b') -> 'b' -'0' 将给出相对数
        3. 求和(初始值为0) (每次我们对 char 执行操作时 -> a=a*10

        【讨论】:

        • 嗨!你能解释一下第2步和第3步吗?谢谢
        【解决方案9】:

        利用 Java 以相同方式使用 char 和 int 的事实。基本上,执行 char - '0' 来获取 char 的 int 值。

        public class StringToInteger {
            public static void main(String[] args) {
                int i = myStringToInteger("123");
                System.out.println("String decoded to number " + i);
            }
        
            public static int myStringToInteger(String str) {
                int sum = 0;
                char[] array = str.toCharArray();
                int j = 0;
                for(int i = str.length() - 1 ; i >= 0 ; i--){
                    sum += Math.pow(10, j)*(array[i]-'0');
                    j++;
                }
                return sum;
            }
        }
        

        【讨论】:

          【解决方案10】:
          public int myStringToInteger(String str) throws NumberFormatException 
          {
              int decimalRadix = 10; //10 is the radix of the decimal system
          
              if (str == null) {
                  throw new NumberFormatException("null");
              }
          
              int finalResult = 0;
              boolean isNegative = false;
              int index = 0, strLength = str.length();
          
              if (strLength > 0) {
                  if (str.charAt(0) == '-') {
                      isNegative = true;
                      index++;
                  } 
          
                  while (index < strLength) {
          
                      if((Character.digit(str.charAt(index), decimalRadix)) != -1){   
                          finalResult *= decimalRadix;
                          finalResult += (str.charAt(index) - '0');
                      } else throw new NumberFormatException("for input string " + str);
          
                      index++;
                  }
          
              } else {
                  throw new NumberFormatException("Empty numeric string");
              }
          
              if(isNegative){
                  if(index > 1)
                      return -finalResult;
                  else
                      throw new NumberFormatException("Only got -");
              }
          
              return finalResult;
          }
          

          结果: 1) 对于输入“34567”,最终结果为:34567 2) 对于输入“-4567”,最终结果为:-4567 3) 对于输入“-”,最终结果将是:java.lang.NumberFormatException: Only got - 4) 对于输入“12ab45”,最终结果将是:java.lang.NumberFormatException: for input string 12ab45

          【讨论】:

            【解决方案11】:
            public static int convertToInt(String input){
                    char[] ch=input.toCharArray();
                    int result=0;
                    for(char c : ch){
                        result=(result*10)+((int)c-(int)'0');
                    }
                    return result;
                }
            

            【讨论】:

              【解决方案12】:

              也许这种方式会快一点:

              public static int convertStringToInt(String num) {
                   int result = 0;
              
                   for (char c: num.toCharArray()) {
                      c -= 48;
                      if (c <= 9) {
                          result = (result << 3) + (result << 1) + c;
                      } else return -1;
                  }
                  return result;
              }
              

              【讨论】:

                【解决方案13】:

                这是一个完整的程序,所有条件为正、负,不使用库

                import java.util.Scanner;
                public class StringToInt {
                 public static void main(String args[]) {
                  String inputString;
                  Scanner s = new Scanner(System.in);
                  inputString = s.nextLine();
                
                  if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
                   System.out.println("error!!!");
                  } else {
                   Double result2 = getNumber(inputString);
                   System.out.println("result = " + result2);
                  }
                
                 }
                 public static Double getNumber(String number) {
                  Double result = 0.0;
                  Double beforeDecimal = 0.0;
                  Double afterDecimal = 0.0;
                  Double afterDecimalCount = 0.0;
                  int signBit = 1;
                  boolean flag = false;
                
                  int count = number.length();
                  if (number.charAt(0) == '-') {
                   signBit = -1;
                   flag = true;
                  } else if (number.charAt(0) == '+') {
                   flag = true;
                  }
                  for (int i = 0; i < count; i++) {
                   if (flag && i == 0) {
                    continue;
                
                   }
                   if (afterDecimalCount == 0.0) {
                    if (number.charAt(i) - '.' == 0) {
                     afterDecimalCount++;
                    } else {
                     beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
                    }
                
                   } else {
                    afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
                    afterDecimalCount = afterDecimalCount * 10;
                   }
                  }
                  if (afterDecimalCount != 0.0) {
                   afterDecimal = afterDecimal / afterDecimalCount;
                   result = beforeDecimal + afterDecimal;
                  } else {
                   result = beforeDecimal;
                  }
                
                  return result * signBit;
                 }
                }
                

                【讨论】:

                  【解决方案14】:
                  Works for Positive and Negative String Using TDD
                  
                  //Solution
                  
                  public int convert(String string) {
                      int number = 0;
                      boolean isNegative = false;
                      int i = 0;
                      if (string.charAt(0) == '-') {
                          isNegative = true;
                          i++;
                      }
                  
                      for (int j = i; j < string.length(); j++) {
                          int value = string.charAt(j) - '0';
                          number *= 10;
                          number += value;
                      }
                      if (isNegative) {
                          number = -number;
                      }
                  
                      return number;
                  }
                  

                  //测试用例

                  public class StringtoIntTest {
                  private StringtoInt stringtoInt;
                  
                  
                  @Before
                  public void setUp() throws Exception {
                  stringtoInt = new StringtoInt();
                  }
                  
                  @Test
                  public void testStringtoInt() {
                      int excepted = stringtoInt.convert("123456");
                      assertEquals(123456,excepted);
                  }
                  
                  @Test
                  public void testStringtoIntWithNegative() {
                      int excepted = stringtoInt.convert("-123456");
                      assertEquals(-123456,excepted);
                  }
                  

                  }

                  【讨论】:

                    【解决方案15】:
                        //Take one positive or negative number
                        String str="-90997865";
                    
                        //Conver String into Character Array
                        char arr[]=str.toCharArray();
                    
                        int no=0,asci=0,res=0;
                    
                        for(int i=0;i<arr.length;i++)
                        {
                           //If First Character == negative then skip iteration and i++
                           if(arr[i]=='-' && i==0)
                           {
                               i++;
                           }
                    
                               asci=(int)arr[i]; //Find Ascii value of each Character 
                               no=asci-48; //Now Substract the Ascii value of 0 i.e 48  from asci
                               res=res*10+no; //Conversion for final number
                        }
                    
                        //If first Character is negative then result also negative
                        if(arr[0]=='-')
                        {
                            res=-res;
                        }
                    
                        System.out.println(res);
                    

                    【讨论】:

                    • 虽然这段代码 sn-p 可以解决问题,但including an explanation 确实有助于提高帖子的质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。也请尽量不要用解释性的 cmets 挤满你的代码,这会降低代码和解释的可读性!
                    【解决方案16】:
                    public class ConvertInteger {
                    
                    public static int convertToInt(String numString){
                        int answer = 0, factor = 1;
                    
                        for (int i = numString.length()-1; i >= 0; i--) {
                            answer += (numString.charAt(i) - '0') *factor;
                            factor *=10;
                        }
                        return answer;
                    }
                    
                    public static void main(String[] args) {
                    
                        System.out.println(convertToInt("789"));
                    }
                    

                    }

                    【讨论】:

                    • 请不要只发布代码作为答案,而是解释不同之处以及它如何解决问题。
                    • 对于 OP 或未来的 Google 员工来说,并不总是清楚代码唯一的答案与其他人有何不同。为避免这种混淆,请花一些时间解释您的代码为何或如何解决问题。
                    • 此函数将字符串数字转换为整数,而无需使用 java 内置函数来进行数学、字符串操作、数字格式化或打印。请执行程序。
                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-09-24
                    • 2011-07-01
                    • 2023-03-13
                    • 2013-10-23
                    相关资源
                    最近更新 更多