JavaEar 专注于收集分享传播有价值的技术资料

如何在Java中将String转换为int? (How to convert a String to an int in Java?)

问题描述


英文原文

How can I convert a String to an int in Java?

My String contains only numbers and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.


中文翻译

如何在Java中将 String 转换为 int

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

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

How can I convert a String to an int in Java?

My String contains only numbers and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

如何在Java中将 String 转换为 int

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

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

31个回答

    最佳答案
  1. Guava has tryParse(String), which returns null if the string couldn't be parsed, for example:

    Integer fooInt = Ints.tryParse(fooString);
    if (fooInt != null) {
      ...
    }
    
  2. 参考答案2
  3. Just for fun: You can use Java 8's Optional for converting a String into an 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.
    

    Here we just combine Integer.valueOf and Optinal. Probably there might be situations when this is useful - for example when you want to avoid null checks. Pre Java 8 code will look like this:

    Integer value = (str == null) ? -1 : Integer.parseInt(str);
    
  4. 参考答案3
  5. Do it manually:

    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;
    }
    
  6. 参考答案4
  7. You can also begin by removing all non-numerical characters and then parsing the int:

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

    But be warned that this only works for non-negative numbers.

  8. 参考答案5
  9. Apart from these above answers, I would like to add several functions:

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

    And here are results while you running them:

      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
      }
    
  10. 参考答案6
  11. You can use new Scanner("1244").nextInt(). Or ask if even an int exists: new Scanner("1244").hasNextInt()

  12. 参考答案7
  13. For example, here are two ways:

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

    There is a slight difference between these methods:

    • valueOf returns a new or cached instance of java.lang.Integer
    • parseInt returns primitive int.

    The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

  14. 参考答案8
  15. You can use this code also, with some precautions.

    • Option #1: Handle the exception explicitly, for example, showing a message dialog and then stop the execution of the current workflow. For example:

      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;
      }
      
    • Option #2: Reset the affected variable if the execution flow can continue in case of an exception. For example, with some modifications in the catch block

      catch (NumberFormatException ex) {
          integerValue = 0;
      }
      

    Using a string constant for comparison or any sort of computing is always a good idea, because a constant never returns a null value.

  16. 参考答案9
  17. As mentioned Apache Commons NumberUtils can do it. Which return 0 if it cannot convert string to int.

    You can also define your own default value.

    NumberUtils.toInt(String str, int defaultValue)
    

    example:

    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. 参考答案10
  19. Methods to do that:

    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 produces Integer object, all other methods - primitive int.

    Last 2 methods from commons-lang3 and big article about converting here.

  20. 参考答案11
  21. Use Integer.parseInt(yourString)

    Remember following things:

    Integer.parseInt("1"); // ok

    Integer.parseInt("-1"); // ok

    Integer.parseInt("+1"); // ok

    Integer.parseInt(" 1"); // Exception (blank space)

    Integer.parseInt("2147483648"); // Exception (Integer is limited to a maximum value of 2,147,483,647)

    Integer.parseInt("1.1"); // Exception (. or , or whatever is not allowed)

    Integer.parseInt(""); // Exception (not 0 or something)

    There is only one type of exception: NumberFormatException

  22. 参考答案12
  23. Here we go

    String str="1234";
    int number = Integer.parseInt(str);
    print number;//1234
    
  24. 参考答案13
  25. In programming competitions, where you're assured that number will always be a valid integer, then you can write your own method to parse input. This will skip all validation related code (since you don't need any of that) and will be a bit more efficient.

    1. For valid positive integer:

      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;
      }
      
    2. For both positive and negative integers:

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

       

    3. If you are expecting a whitespace before or after these numbers, then make sure to do a str = str.trim() before processing further.

  26. 参考答案14
  27. int foo = Integer.parseInt("1234");
    

    See the Java Documentation for more information.

    (If you have it in a StringBuilder (or the ancient StringBuffer), you'll need to do Integer.parseInt(myBuilderOrBuffer.toString()); instead).

  28. 参考答案15
  29. int foo=Integer.parseInt("1234");
    

    Make sure there is no non-numeric data in the string.

  30. 参考答案16
  31. Currently I'm doing an assignment for college, where I can't use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It's a far more complex code, but it could help others that are restricted like I was.

    The first thing to do is to receive the input, in this case, a string of digits; I'll call it String number, and in this case, I'll exemplify it using the number 12, therefore String number = "12";

    Another limitation was the fact that I couldn't use repetitive cycles, therefore, a for cycle (which would have been perfect) can't be used either. This limits us a bit, but then again, that's the goal. Since I only needed two digits (taking the last two digits), a simple charAtsolved it:

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

    Having the codes, we just need to look up at the table, and make the necessary adjustments:

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

    Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn't any mathematic operation that we can do.

    We're dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:

     lastdigit = lastdigit/10;
    

    This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:

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

    Without getting too into the math, we're simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:

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

    And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:

    • No repetitive cycles
    • No "Magic" Expressions such as parseInt
  32. 参考答案17
  33. An alternate solution is to use Apache Commons' NumberUtils:

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

    The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

    Apache NumberUtils API Version 3.4

  34. 参考答案18
  35. Integer.decode

    You can also use public static Integer decode(String nm) throws NumberFormatException.

    It also works for base 8 and 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
    

    If you want to get int instead of Integer you can use:

    1. Unboxing:

      int val = Integer.decode("12"); 
      
    2. intValue():

      Integer.decode("12").intValue();
      
  36. 参考答案19
  37. For normal string you can use:

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

    For String builder and String buffer you can use:

    Integer.parseInt(myBuilderOrBuffer.toString());
    
  38. 参考答案20
  39. Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.

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

    It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.

  40. 参考答案21
  41. Converting a string to an int is more complicated than just convertig a number. You have think about the following issues:

    • Does the string only contains numbers 0-9?
    • What's up with -/+ before or after the string? Is that possible (referring to accounting numbers)?
    • What's up with MAX_-/MIN_INFINITY? What will happen if the string is 99999999999999999999? Can the machine treat this string as an int?
  42. 参考答案22
  43. We can use the parseInt(String str) method of the Integer wrapper class for converting a String value to an integer value.

    For example:

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

    The Integer class also provides the valueOf(String str) method:

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

    We can also use toInt(String strValue) of NumberUtils Utility Class for the conversion:

    String strValue = "12345";
    Integer intValue = NumberUtils.toInt(strValue);
    
  44. 参考答案23
  45. I'm have a solution, but I do not know how effective it is. But it works well, and I think you could improve it. On the other hand, I did a couple of tests with JUnit which step correctly. I attached the function and testing:

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

    Testing with 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));
            }
        }
    }
    
  46. 参考答案24
  47. Whenever there is the slightest possibility that the given String does not contain an Integer, you have to handle this special case. Sadly, the standard Java methods Integer::parseInt and Integer::valueOf throw a NumberFormatException to signal this special case. Thus, you have to use exceptions for flow control, which is generally considered bad coding style.

    In my opinion, this special case should be handled by returning an Optional<Integer>. Since Java does not offer such a method, I use the following wrapper:

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

    Usage:

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

    While this is still using exceptions for flow control internally, the usage code becomes very clean.

  48. 参考答案25
  49. One method is parseInt(String) returns a primitive int

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

    Second method is valueOf(String) returns a new Integer() object.

    String number = "10";
    Integer result = Integer.valueOf(number);
    System.out.println(result);
    
  50. 参考答案26
  51. 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;
         }
        }
    
  52. 参考答案27
  53. Use Integer.parseInt() and put it inside a try...catch block to handle any errors just in case a non-numeric character is entered e.g

        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);
        }
     }
    
  54. 参考答案28
  55. Use this line to parse a string value to int:

     String x = "11111111";
     int y = Integer.parseInt(x);
     System.out.println(y);
    
  56. 参考答案29
  57. Simply you can try this:

    • Use Integer.parseInt(your_string); to convert a String to int
    • Use Double.parseDouble(your_string); to convert a STring to double

    Example

    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
    
  58. 参考答案30
  59. Alternatively, you can use Integer.valueOf(). It will return an Integer object.

    String numberStringFormat = "10";
    Integer resultIntFormat = Integer.valueOf(numberStringFormat);
    LOG.info("result:"+result);
    

    Output:

    10

  60. 参考答案31
  61. String s="100";
    try {
     int i=Integer.parseInt( s );
    }catch( Exception e ) {
     System.out.println(e.getMessage());
    }
    
    
    
    String s="100L";
    try {
      int i=Integer.parseInt( s );
     }catch( Exception e ) {
      System.out.println(e.getMessage());
    }