首页 文章

如何在Java中将String转换为int?

提问于
浏览
2668

如何在Java中将 String 转换为 int

我的字符串只包含数字,我想返回它代表的数字 .

例如,给定字符串 "1234" ,结果应该是数字 1234 .

30 回答

  • 11

    Guava有tryParse(String),如果无法解析字符串,则返回 null ,例如:

    Integer fooInt = Ints.tryParse(fooString);
    if (fooInt != null) {
      ...
    }
    
  • 226

    顺便提一下,请注意,如果字符串为null,则调用:

    int i = Integer.parseInt(null);
    

    抛出NumberFormatException,而不是NullPointerException .

  • 618
    String myString = "1234";
    int foo = Integer.parseInt(myString);
    

    有关更多信息,请参见Java Documentation .

  • 9

    在编程竞赛中,您可以确保数字始终是有效整数,那么您可以编写自己的方法来解析输入 . 这将跳过所有与验证相关的代码(因为您不需要任何相关代码)并且会更有效率 .

    • 对于有效的正整数:
    private static int parseInt(String str) {
        int i, n = 0;
    
        for (i = 0; i < str.length(); i++) {
            n *= 10;
            n += str.charAt(i) - 48;
        }
        return n;
    }
    
    • 对于正整数和负整数:
    private static int parseInt(String str) {
        int i=0, n=0, sign=1;
        if(str.charAt(0) == '-') {
            i=1;
            sign=-1;
        }
        for(; i<str.length(); i++) {
            n*=10;
            n+=str.charAt(i)-48;
        }
        return sign*n;
    }
    
    • 如果您希望在这些数字之前或之后有空格,那么请确保在进一步处理之前执行 str = str.trim() .
  • 7

    我有点意外,没有人提到将String作为参数的Integer构造函数 .
    所以,这是:

    String myString = "1234";
    int i1 = new Integer(myString);
    

    Java 8 - Integer(String) .

    当然,构造函数将返回 Integer 类型,并且取消装箱操作会将值转换为 int .


    值得一提的是
    此构造函数调用 parseInt 方法 .

    public Integer(String var1) throws NumberFormatException {
        this.value = parseInt(var1, 10);
    }
    
  • 20

    例如,有两种方法:

    Integer x = Integer.valueOf(str);
    // or
    int y = Integer.parseInt(str);
    

    这些方法之间略有不同:

    • valueOf 返回 java.lang.Integer 的新缓存实例

    • parseInt 返回原始 int .

    所有情况都是如此: Short.valueOf / parseShortLong.valueOf / parseLong 等 .

  • 7

    Integer.decode

    你也可以使用 public static Integer decode(String nm) throws NumberFormatException .

    它也适用于基数8和16:

    // base 10
    Integer.parseInt("12");     // 12 - int
    Integer.valueOf("12");      // 12 - Integer
    Integer.decode("12");       // 12 - Integer
    // base 8
    // 10 (0,1,...,7,10,11,12)
    Integer.parseInt("12", 8);  // 10 - int
    Integer.valueOf("12", 8);   // 10 - Integer
    Integer.decode("012");      // 10 - Integer
    // base 16
    // 18 (0,1,...,F,10,11,12)
    Integer.parseInt("12",16);  // 18 - int
    Integer.valueOf("12",16);   // 18 - Integer
    Integer.decode("#12");      // 18 - Integer
    Integer.decode("0x12");     // 18 - Integer
    Integer.decode("0X12");     // 18 - Integer
    // base 2
    Integer.parseInt("11",2);   // 3 - int
    Integer.valueOf("11",2);    // 3 - Integer
    

    如果你想得到 int 而不是 Integer 你可以使用:

    • 取消装箱:
    int val = Integer.decode("12");
    
    • intValue()
    Integer.decode("12").intValue();
    
  • 22

    方法:

    1. Integer.parseInt(s)
     2. Integer.parseInt(s, radix)
     3. Integer.parseInt(s, beginIndex, endIndex, radix)
     4. Integer.parseUnsignedInt(s)
     5. Integer.parseUnsignedInt(s, radix)
     6. Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
     7. Integer.valueOf(s)
     8. Integer.valueOf(s, radix)
     9. Integer.decode(s)
     10. NumberUtils.toInt(s)
     11. NumberUtils.toInt(s, defaultValue)
    

    Integer.valueOf生成Integer对象,所有其他方法 - primitive int .

    来自commons-lang3的最后2个方法和关于转换here的大文章 .

  • 6

    我们可以使用 Integer 包装类的 parseInt(String str) 方法将String值转换为整数值 .

    例如:

    String strValue = "12345";
    Integer intValue = Integer.parseInt(strVal);
    

    Integer 类还提供了 valueOf(String str) 方法:

    String strValue = "12345";
    Integer intValue = Integer.valueOf(strValue);
    

    我们也可以使用 toInt(String strValue)NumberUtils Utility Class进行转换:

    String strValue = "12345";
    Integer intValue = NumberUtils.toInt(strValue);
    
  • 9

    你可以试试这个:

    • 使用 Integer.parseInt(your_string);String 转换为 int

    • 使用 Double.parseDouble(your_string);String 转换为 double

    示例

    String str = "8955";
    int q = Integer.parseInt(str);
    System.out.println("Output>>> " + q); // Output: 8955
    

    String str = "89.55";
    double q = Double.parseDouble(str);
    System.out.println("Output>>> " + q); // Output: 89.55
    
  • 37

    一种方法是parseInt(String)返回一个原语int

    String number = "10";
    int result = Integer.parseInt(number);
    System.out.println(result);
    

    第二种方法是valueOf(String)返回一个新的Integer()对象 .

    String number = "10";
    Integer result = Integer.valueOf(number);
    System.out.println(result);
    
  • 9

    目前我正在为大学做作业,在那里我不能使用某些表达式,例如上面的表达式,通过查看ASCII表,我设法做到了 . 这是一个复杂得多的代码,但它可以帮助像我一样受限制的其他代码 .

    首先要做的是接收输入,在这种情况下,是一串数字;我将其称为 String number ,在这种情况下,我将使用数字12来举例说明,因此 String number = "12";

    另一个限制是我无法使用重复循环,因此, for 循环(本来是完美的)可以实现目标 . 由于我只需要两位数(取最后两位数字),一个简单的 charAt 解决了它:

    // Obtaining the integer values of the char 1 and 2 in ASCII
     int semilastdigitASCII = number.charAt(number.length()-2);
     int lastdigitASCII = number.charAt(number.length()-1);
    

    有了代码,我们只需要查看表格,并进行必要的调整:

    double semilastdigit = semilastdigitASCII - 48;  //A quick look, and -48 is the key
     double lastdigit = lastdigitASCII - 48;
    

    现在,为什么加倍?好吧,因为一个非常“奇怪”的步骤 . 目前我们有两个双打,1和2,但是我们需要把它变成12,我们可以做任何数学运算 .

    我们将后者(lastdigit)除以时尚 2/10 = 0.2 (因此为什么加倍)这样:

    lastdigit = lastdigit/10;
    

    这只是玩数字 . 我们把最后一位数字变成了小数 . 但现在,看看会发生什么:

    double jointdigits = semilastdigit + lastdigit; // 1.0 + 0.2 = 1.2
    

    没有太多的数学,我们只是将数字与数字隔离 . 你看,因为我们只考虑0-9,除以10的倍数就像创建一个存储它的“盒子”(当你的一年级老师解释你是一个单位和一百个是什么时,回想一下) . 所以:

    int finalnumber = (int) (jointdigits*10); // Be sure to use parentheses "()"
    

    你去吧考虑到以下限制,您将一个数字字符串(在本例中为两位数)转换为由这两个数字组成的整数:

    • 没有重复循环

    • 否"Magic"表达式如parseInt

  • 15

    使用Integer.parseInt(yourString)

    Remember following things:

    Integer.parseInt("1"); //好的

    Integer.parseInt("-1"); //好的

    Integer.parseInt("+1"); //好的

    Integer.parseInt(" 1"); //异常(空格)

    Integer.parseInt("2147483648"); //异常(整数仅限于maximum value,2,147,483,647)

    Integer.parseInt("1.1"); //异常( ., 或其他不允许的内容)

    Integer.parseInt(""); //异常(不是0或者什么)

    只有一种类型的例外:NumberFormatException

  • 3713

    您也可以先删除所有非数字字符,然后解析int:

    string mystr = mystr.replaceAll( "[^\\d]", "" );
    int number= Integer.parseInt(mystr);
    

    但请注意,这仅适用于非负数 .

  • 7

    使用Integer.parseInt()并将其放在 try...catch 块中以处理任何错误,以防万一输入非数字字符,例如,

    private void ConvertToInt(){
        String string = txtString.getText();
        try{
            int integerValue=Integer.parseInt(string);
            System.out.println(integerValue);
        }
        catch(Exception e){
           JOptionPane.showMessageDialog(
             "Error converting string to integer\n" + e.toString,
             "Error",
             JOptionPane.ERROR_MESSAGE);
        }
     }
    
  • 21

    对于普通字符串,您可以使用:

    int number = Integer.parseInt("1234");
    

    对于String builder和String buffer,您可以使用:

    Integer.parseInt(myBuilderOrBuffer.toString());
    
  • 9

    只是为了好玩:你可以使用Java 8的 OptionalString 转换为 Integer

    String str = "123";
    Integer value = Optional.of(str).map(Integer::valueOf).get();
    // Will return the integer value of the specified string, or it
    // will throw an NPE when str is null.
    
    value = Optional.ofNullable(str).map(Integer::valueOf).orElse(-1);
    // Will do the same as the code above, except it will return -1
    // when srt is null, instead of throwing an NPE.
    

    这里我们只结合 Integer.valueOfOptinal . 可能存在这种情况有用的情况 - 例如,当您想要避免空检查时 . Pre Java 8代码如下所示:

    Integer value = (str == null) ? -1 : Integer.parseInt(str);
    
  • 30

    另一种解决方案是使用Apache Commons' NumberUtils:

    int num = NumberUtils.toInt("1234");
    

    Apache实用程序很好,因为如果字符串是无效的数字格式,则始终返回0 . 因此保存try catch块 .

    Apache NumberUtils API Version 3.4

  • 24

    This is Complete program with all conditions positive, negative without using library

    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("Not a Number");
          } 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;
         }
        }
    
  • 5

    好吧,需要考虑的一个非常重要的一点是,整数解析器抛出了Javadoc中所述的NumberFormatException .

    int foo;
    String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
    String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
    try {
          foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
    } catch (NumberFormatException e) {
          //Will Throw exception!
          //do something! anything to handle the exception.
    }
    
    try {
          foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
    } catch (NumberFormatException e) {
          //No problem this time, but still it is good practice to care about exceptions.
          //Never trust user input :)
          //Do something! Anything to handle the exception.
    }
    

    尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要 .

  • 6

    手动完成:

    public static int strToInt( String str ){
        int i = 0;
        int num = 0;
        boolean isNeg = false;
    
        //Check for negative sign; if it's there, set the isNeg flag
        if (str.charAt(0) == '-') {
            isNeg = true;
            i = 1;
        }
    
        //Process each character of the string;
        while( i < str.length()) {
            num *= 10;
            num += str.charAt(i++) - '0'; //Minus the ASCII code of '0' to get the value of the charAt(i++).
        }
    
        if (isNeg)
            num = -num;
        return num;
    }
    
  • 3

    你可以使用 new Scanner("1244").nextInt() . 或者询问是否存在int: new Scanner("1244").hasNextInt()

  • 4

    只要给定String不包含Integer的可能性最小,就必须处理这种特殊情况 . 遗憾的是,标准的Java方法 Integer::parseIntInteger::valueOf 抛出一个 NumberFormatException 来表示这种特殊情况 . 因此,您必须使用流控制的异常,这通常被认为是错误的编码风格 .

    在我看来,这个特殊情况应该通过返回 Optional<Integer> 来处理 . 由于Java不提供这样的方法,我使用以下包装器:

    private Optional<Integer> tryParseInteger(String string) {
        try {
            return Optional.of(Integer.valueOf(string));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }
    

    用法:

    // prints 1234
    System.out.println(tryParseInteger("1234").orElse(-1));
    // prints -1
    System.out.println(tryParseInteger("foobar").orElse(-1));
    

    虽然这仍然在内部使用流控制的异常,但使用代码变得非常干净 .

  • 40

    如前所述,Apache Commons NumberUtils 可以做到 . 如果它不能将字符串转换为int,则返回 0 .

    您还可以定义自己的默认值 .

    NumberUtils.toInt(String str, int defaultValue)
    

    例:

    NumberUtils.toInt("3244", 1) = 3244
    NumberUtils.toInt("", 1)     = 1
    NumberUtils.toInt(null, 5)   = 5
    NumberUtils.toInt("Hi", 6)   = 6
    NumberUtils.toInt(" 32 ", 1) = 1 //space in numbers are not allowed
    NumberUtils.toInt(StringUtils.trimToEmpty( "  32 ",1)) = 32;
    
  • 18

    将字符串转换为int比仅转换数字更复杂 . 您已经考虑过以下问题:

    • 字符串是否只包含数字 0-9

    • 字符串之前或之后的 -/+ 是什么?这是可能的(指会计数字)?

    • 怎么了 MAX_-/MIN_INFINITY? 如果字符串是99999999999999999999会怎么样?机器可以将此字符串视为int吗?

  • 16

    除了以上这些答案,我想添加几个功能:

    public static int parseIntOrDefault(String value, int defaultValue) {
        int result = defaultValue;
        try {
          result = Integer.parseInt(value);
        } catch (Exception e) {
    
        }
        return result;
      }
    
      public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) {
        int result = defaultValue;
        try {
          String stringValue = value.substring(beginIndex);
          result = Integer.parseInt(stringValue);
        } catch (Exception e) {
    
        }
        return result;
      }
    
      public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) {
        int result = defaultValue;
        try {
          String stringValue = value.substring(beginIndex, endIndex);
          result = Integer.parseInt(stringValue);
        } catch (Exception e) {
    
        }
        return result;
      }
    

    以下是运行它们时的结果:

    public static void main(String[] args) {
        System.out.println(parseIntOrDefault("123", 0)); // 123
        System.out.println(parseIntOrDefault("aaa", 0)); // 0
        System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456
        System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789
      }
    
  • 14

    您也可以使用此代码,并采取一些预防措施 .

    • 选项#1:显式处理异常,例如,显示消息对话框,然后停止执行当前工作流 . 例如:
    try
        {
            String stringValue = "1234";
    
            // From String to Integer
            int integerValue = Integer.valueOf(stringValue);
    
            // Or
            int integerValue = Integer.ParseInt(stringValue);
    
            // Now from integer to back into string
            stringValue = String.valueOf(integerValue);
        }
    catch (NumberFormatException ex) {
        //JOptionPane.showMessageDialog(frame, "Invalid input string!");
        System.out.println("Invalid input string!");
        return;
    }
    
    • 选项#2:如果在异常情况下执行流程可以继续,则重置受影响的变量 . 例如,在catch块中进行一些修改
    catch (NumberFormatException ex) {
        integerValue = 0;
    }
    

    使用字符串常量进行比较或任何类型的计算总是一个好主意,因为常量永远不会返回空值 .

  • 5

    开始了

    String str="1234";
    int number = Integer.parseInt(str);
    print number;//1234
    
  • 18

    我有一个解决方案,但我不知道它有多有效 . 但它运作良好,我认为你可以改善它 . 另一方面,我用JUnit进行了几次测试,这是正确的 . 我附上了功能和测试:

    static public Integer str2Int(String str) {
        Integer result = null;
        if (null == str || 0 == str.length()) {
            return null;
        }
        try {
            result = Integer.parseInt(str);
        } 
        catch (NumberFormatException e) {
            String negativeMode = "";
            if(str.indexOf('-') != -1)
                negativeMode = "-";
            str = str.replaceAll("-", "" );
            if (str.indexOf('.') != -1) {
                str = str.substring(0, str.indexOf('.'));
                if (str.length() == 0) {
                    return (Integer)0;
                }
            }
            String strNum = str.replaceAll("[^\\d]", "" );
            if (0 == strNum.length()) {
                return null;
            }
            result = Integer.parseInt(negativeMode + strNum);
        }
        return result;
    }
    

    使用JUnit进行测试:

    @Test
    public void testStr2Int() {
        assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
        assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
        assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
        assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
        assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
        assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
        assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
        assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
        assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
        assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
        assertEquals("Not
         is numeric", null, Helper.str2Int("czv.,xcvsa"));
        /**
         * Dynamic test
         */
        for(Integer num = 0; num < 1000; num++) {
            for(int spaces = 1; spaces < 6; spaces++) {
                String numStr = String.format("%0"+spaces+"d", num);
                Integer numNeg = num * -1;
                assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
                assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
            }
        }
    }
    
  • 80
    int foo=Integer.parseInt("1234");
    

    确保字符串中没有非数字数据 .

相关问题