如何在Java中将字符串转换为int?

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

在Java中,如何将EDCOX1的0度转换为EDCOX1×1?

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

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


1
2
String myString ="1234";
int foo = Integer.parseInt(myString);

如果您查看Java文档,您会注意到"catch"是,这个函数可以抛出EDCOX1,0,当然,您必须处理:

1
2
3
4
5
6
7
8
int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)
{
   foo = 0;
}

(这种处理方法默认为0的一个格式错误的数字,但如果您愿意,您可以做其他的事情。)

或者,您可以从Guava库中使用EDCOX1 2的方法,该方法结合Java 8的EDCOX1引用3,使得将字符串转换成INT:

1
2
3
4
5
import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)


例如,有两种方法:

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

这些方法之间存在细微差别:

  • valueOf返回java.lang.Integer的新实例或缓存实例。
  • parseInt返回原始int

所有情况都一样:Short.valueOf/parseShortLong.valueOf/parseLong等。


好吧,需要考虑的一个非常重要的点是,整数解析器会像javadoc中所述那样抛出numberFormatException。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
}

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


手动完成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}


目前我正在为大学做一个作业,在那里我不能使用某些表达式,比如上面的表达式,通过查看ASCII表,我成功地完成了这个任务。这是一个更复杂的代码,但它可以帮助像我一样受到限制的其他人。

首先要做的是接收输入,在本例中是一个数字串;我将它称为String number,在本例中,我将使用数字12来举例说明,因此String number ="12";

另一个限制是我不能使用重复循环,因此,for循环(本来是完美的)也不能使用。这限制了我们一点,但再一次,这就是我们的目标。因为我只需要两位数(取最后两位数),所以一个简单的charAt就解决了:

1
2
3
 // 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);

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

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

现在,为什么要加倍?嗯,因为一个非常"奇怪"的步骤。目前我们有两个双打,1和2,但是我们需要把它转换成12,我们不能做任何数学运算。

我们将后一个数字(最后一个数字)除以10,方法是2/10 = 0.2(因此为什么是double),如下所示:

1
 lastdigit = lastdigit/10;

这只是玩弄数字而已。我们正在把最后一个数字转换成十进制。但是现在,看看会发生什么:

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

在不太深入数学的情况下,我们只是简单地将一个数的位数隔离开来。你看,因为我们只考虑0-9,除以10的倍数就好像在你存储它的地方创建了一个"盒子"(回想一下当你的一年级老师向你解释一个单位和一百个单位时)。所以:

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

就这样。考虑到以下限制,您将一个数字串(在本例中是两个数字)转换为由这两个数字组成的整数:

  • 无重复循环
  • 没有"magic"表达式,如parseint


另一种解决方案是使用ApacheCommons的numberUtils:

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

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

Apache NumberUtils API 3.4版


Integer.decode

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

它也适用于8基和16基:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 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,你可以使用:

  • 拆箱:

    1
    int val = Integer.decode("12");
  • intValue()

    1
    Integer.decode("12").intValue();

  • 只要给定字符串不包含整数的可能性极小,就必须处理这种特殊情况。可悲的是,标准的Java方法EDOCX1 10和EDCOX1 OR 11抛出一个EDCOX1×12来表示这种特殊情况。因此,您必须为流控制使用异常,这通常被认为是糟糕的编码风格。

    在我看来,这种特殊情况应该通过退回一个Optional来处理。由于Java不提供这样的方法,所以我使用以下包装器:

    1
    2
    3
    4
    5
    6
    7
    private Optional<Integer> tryParseInteger(String string) {
        try {
            return Optional.of(Integer.valueOf(string));
        } catch (NumberFormatException e) {
            return Optional.empty();
        }
    }

    用途:

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

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


    将字符串转换为int要比只转换数字复杂得多。您已经考虑了以下问题:

    • 字符串是否只包含数字0-9?
    • 弦前后的-/+是怎么回事?有可能吗(指会计数字)?
    • 最大/最小无穷大是怎么回事?如果字符串是9999999999999999,会发生什么?机器能把这个字符串当作int吗?


    方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     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。

    最后2个方法来自commons-lang3和有关转换的大文章。


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

    例如:

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

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

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

    我们还可以使用numberutils实用程序类的toInt(String strValue)进行转换:

    1
    2
    String strValue ="12345";
    Integer intValue = NumberUtils.toInt(strValue);

    使用Integer.parseInt(yourString)

    记住以下事项:

    Integer.parseInt("1");好的

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

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

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

    Integer.parseInt("2147483648");//异常(整数限制为2147483647的最大值)

    Integer.parseInt("1.1");//例外(.或者,或者任何不允许的东西)

    Integer.parseInt("");//例外(不是0或其他)

    只有一种例外:NumberFormatException


    我有一个解决方案,但我不知道它有多有效。但效果很好,我认为你可以改进它。另一方面,我用JUnit做了一些测试,测试步骤是正确的。我附上了功能和测试:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    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测试:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    @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));
            }
        }
    }


    仅仅是为了好玩:您可以使用Java 8的EDCOX1 OR 17来将EDCOX1的18度转换成EDCOX1×1:

    1
    2
    3
    4
    5
    6
    7
    8
    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结合起来。可能在某些情况下,这是有用的-例如,当您想避免空检查时。前Java 8代码将是这样的:

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


    guava有triparse(string),如果无法解析该字符串,则返回null,例如:

    1
    2
    3
    4
    Integer fooInt = Ints.tryParse(fooString);
    if (fooInt != null) {
      ...
    }

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

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

    但请注意,这只适用于非负数。


    除了上述答案,我还想添加几个函数。这些是使用它们时的结果:

    1
    2
    3
    4
    5
    6
      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
      }

    实施:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
       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;
      }

    您可以使用new Scanner("1244").nextInt()。或询问是否存在利息:new Scanner("1244").hasNextInt()


    在编程竞赛中,如果您确信数字总是一个有效的整数,那么您可以编写自己的方法来解析输入。这将跳过所有与验证相关的代码(因为您不需要这些代码),并且效率会更高。

  • 对于有效的正整数:

    1
    2
    3
    4
    5
    6
    7
    8
    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;
    }
  • 对于正整数和负整数:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    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;
    }

    nbsp;

  • 如果您希望在这些数字之前或之后有空格,然后确保在进一步处理之前执行str = str.trim()


  • 如前所述,ApacheCommons(14)可以做到这一点。如果字符串不能转换为int,则返回0

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

    1
    NumberUtils.toInt(String str, int defaultValue)

    例子:

    1
    2
    3
    4
    5
    6
    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;

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

    • 选项1:显式处理异常,例如,显示消息对话框,然后停止执行当前工作流。例如:

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      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块中进行了一些修改

      1
      2
      3
      catch (NumberFormatException ex) {
          integerValue = 0;
      }

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


    1
    int foo=Integer.parseInt("1234");

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


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

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

    对于字符串生成器和字符串缓冲区,可以使用:

    1
    Integer.parseInt(myBuilderOrBuffer.toString());

    您只需尝试一下:

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

    例子

    1
    2
    3
    String str ="8955";
    int q = Integer.parseInt(str);
    System.out.println("Output>>>" + q); // Output: 8955
    1
    2
    3
    String str ="89.55";
    double q = Double.parseDouble(str);
    System.out.println("Output>>>" + q); // Output: 89.55


    我有点惊讶,没有人提到将字符串作为参数的整数构造函数。所以,这里是:

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

    Java 8 -整数(String)。

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

    重要的是要提到此构造函数调用parseInt方法。

    1
    2
    3
    public Integer(String var1) throws NumberFormatException {
        this.value = parseInt(var1, 10);
    }

    我们走吧

    1
    2
    3
    String str="1234";
    int number = Integer.parseInt(str);
    print number;//1234

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    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
    "
    + e.toString,
            "Error",
             JOptionPane.ERROR_MESSAGE);
        }
     }

    一个方法是parseint(string)返回一个基元int

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

    第二个方法是valueof(string)返回一个新的integer()对象。

    1
    2
    3
    String number ="10";
    Integer result = Integer.valueOf(number);
    System.out.println(result);

    这是一个完整的程序,所有条件都是肯定的,否定的,不使用库

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    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;
         }
        }


    可通过7种方式完成:

    1
    2
    3
    4
    import com.google.common.primitives.Ints;
    import org.apache.commons.lang.math.NumberUtils;

    String number ="999";

    1)使用Ints.tryParse

    1
    int result = Ints.tryParse(number);

    2)使用NumberUtils.createInteger

    1
    Integer result = NumberUtils.createInteger(number);

    3)使用NumberUtils.toInt

    1
    int result = NumberUtils.toInt(number);

    4)使用Integer.valueOf

    1
    Integer result = Integer.valueOf(number);

    5)使用Integer.parseInt

    1
    int result = Integer.parseInt(number);

    6)使用Integer.decode

    1
    int result = Integer.decode(number);

    7)使用Integer.parseUnsignedInt

    1
    int result = Integer.parseUnsignedInt(number);


    您可以使用以下任何一种:

  • Integer.parseInt(s)
  • Integer.parseInt(s, radix)
  • Integer.parseInt(s, beginIndex, endIndex, radix)
  • Integer.parseUnsignedInt(s)
  • Integer.parseUnsignedInt(s, radix)
  • Integer.parseUnsignedInt(s, beginIndex, endIndex, radix)
  • Integer.valueOf(s)
  • Integer.valueOf(s, radix)
  • Integer.decode(s)
  • NumberUtils.toInt(s)
  • NumberUtils.toInt(s, defaultValue)

  • Integer.parseInt(myString);—使用包装类


    另外,请注意,如果字符串为空,则调用:

    1
    int i = Integer.parseInt(null);

    引发NumberFormatException,而不是NullPointerException。


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    import java.util.*;

    public class strToint {

        public static void main(String[] args) {

            String str ="123";
            byte barr[] = str.getBytes();

            System.out.println(Arrays.toString(barr));
            int result = 0;

            for(int i = 0; i < barr.length; i++) {
                //System.out.print(barr[i]+"");
                int ii = barr[i];
                char a = (char) ii;
                int no = Character.getNumericValue(a);
                result = result * 10 + no;
                System.out.println(result);
            }

            System.out.println("result:"+result);
        }
    }


    public static int parseint(string s)引发numberFormatException

    您可以使用Integer.parseInt()将字符串转换为int。

    将字符串20转换为基元int。

    1
    2
    3
        String n ="20";
        int r = Integer.parseInt(n);//returns a primitive int      
        System.out.println(r);

    Output-20

    如果字符串不包含可分析整数。它会抛出NumberFormatException

    1
    2
    3
    String n ="20I";// throwns NumberFormatException
    int r = Integer.parseInt(n);
    System.out.println(r);

    公共静态整数值(字符串)引发NumberFormatException

    您可以使用Integer.valueOf(),其中它将返回一个整数对象。

    1
    2
    3
    String n ="20";
    Integer r = Integer.valueOf(n); //returns a new Integer() object.  
    System.out.println(r);

    Output-20

    工具书类网址:https://docs.oracle.com/en/


    使用此方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    public int ConvertStringToInt(String number) {
        int num = 0;

        try {
            int newNumber = Integer.ParseInt(number);
            num = newNumber;
        } catch(Exception ex) {
            num = 0;
            Log.i("Console",ex.toString);
        }

        return num;
    }

    String转换成Int的一些方法如下:

  • 您可以使用Integer.parseInt()

    String test ="4568";
    int new = Integer.parseInt(test);

  • 也可以使用Integer.valueOf()

    String test ="4568";
    int new =Integer.parseInt(test);


  • 我编写了这个快速方法来将字符串输入解析为int或long。它比当前的jdk 11 integer.parseint或long.parselong更快。尽管您只要求输入int,但我还包含了long解析器。下面的代码解析器要求解析器的方法必须很小才能快速运行。另一个版本低于测试代码。另一个版本非常快,它不依赖于类的大小。

    这个类检查是否溢出,您可以自定义代码以适应您的需要。空字符串将使用我的方法生成0,但这是有意的。你可以改变它来适应你的情况或者按原样使用。

    这只是类中需要parseint和parselong的部分。注意,这只处理基数为10的数字。

    int解析器的测试代码低于下面的代码。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    /*
     * Copyright 2019 Khang Hoang Nguyen
     * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions
     * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
     * THE SOFTWARE IS PROVIDED"AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     * @author: Khang Hoang Nguyen - [email protected].
     **/

    final class faiNumber{        
        private static final long[] longpow = {0L, 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L,
                                               10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L,
                                               1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L,
                                               };

        private static final int[] intpow = { 0, 1, 10, 100, 1000, 10000,
                                              100000, 1000000, 10000000, 100000000, 1000000000
                                            };

        /**
         * parseLong(String str) parse a String into Long.
         * All errors throw by this method is NumberFormatException.
         * Better errors can be made to tailor to each use case.
         **/

        public static long parseLong(final String str) {
            final int length = str.length();
            if ( length == 0 ) return 0L;        

            char c1 = str.charAt(0); int start;

            if ( c1 == '-' || c1 == '+' ){
                if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
                start = 1;
            } else {
                start = 0;
            }
            /*
             * Note: if length > 19, possible scenario is to run through the string
             * to check whether the string contains only valid digits.
             * If the check had only valid digits then a negative sign meant underflow, else, overflow.
             */

            if ( length - start > 19 ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );

            long c;
            long out = 0L;

            for ( ; start < length; start++){
                c = (str.charAt(start) ^ '0');
                if ( c > 9L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
                out += c * longpow[length - start];
            }

            if ( c1 == '-' ){
                out = ~out + 1L;
                // if out > 0 number underflow(supposed to be negative).
                if ( out > 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
                return out;
            }
            // if out < 0 number overflow(supposed to be positive).
            if ( out < 0L ) throw new NumberFormatException( String.format("Not a valid long value. Input '%s'.", str) );
            return out;
        }

        /**
         * parseInt(String str) parse a string into an int.
         * return 0 if string is empty.
         **/

        public static int parseInt(final String str) {
            final int length = str.length();
            if ( length == 0 ) return 0;        

            char c1 = str.charAt(0); int start;

            if ( c1 == '-' || c1 == '+' ){
                if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
                start = 1;
            } else {
                start = 0;
            }

            int out = 0; int c;
            int runlen = length - start;

            if ( runlen > 9 ) {
                if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );

                c = (str.charAt(start) ^ '0');   // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
                if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
                if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
                out += c * intpow[length - start++];
            }

            for ( ; start < length; start++){
                c = (str.charAt(start) ^ '0');
                if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
                out += c * intpow[length - start];
            }

            if ( c1 == '-' ){
                out = ~out + 1;
                if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
                return out;
            }

            if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            return out;
        }
    }

    测试代码部分。这大概需要200秒左右。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // Int Number Parser Test;
    long start = System.currentTimeMillis();    
    System.out.println("INT PARSER TEST");
    for (int i = Integer.MIN_VALUE; i != Integer.MAX_VALUE; i++){
       if( faiNumber.parseInt(""+i) != i ) System.out.println("Wrong");
       if ( i == 0 ) System.out.println("HalfWay Done");
    }

    if( faiNumber.parseInt(""+Integer.MAX_VALUE) != Integer.MAX_VALUE ) System.out.println("Wrong");
    long end = System.currentTimeMillis();
    long result = (end - start);
    System.out.println(result);        
    // INT PARSER END */

    另一种方法也很快。注意,不使用int-pow数组,而是使用10乘移位的数学优化。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    public static int parseInt(final String str) {
        final int length = str.length();
        if ( length == 0 ) return 0;        

        char c1 = str.charAt(0); int start;

        if ( c1 == '-' || c1 == '+' ){
            if ( length == 1 ) throw new NumberFormatException( String.format("Not a valid integer value. Input '%s'.", str) );
            start = 1;
        } else {
            start = 0;
        }

        int out = 0; int c;
        while( start < length && str.charAt(start) == '0' ) start++; // <-- This to disregard leading 0, can be removed if you know exactly your source does not have leading zeroes.
        int runlen = length - start;

        if ( runlen > 9 ) {
            if ( runlen > 10 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );

            c = (str.charAt(start++) ^ '0');   // <- Any number from 0 - 255 ^ 48 will yield greater than 9 except 48 - 57
            if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            if ( c > 2 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            out = (out << 1) + (out << 3) + c; // <- alternatively this can just be out = c or c above can just be out;
        }

        for ( ; start < length; start++){
            c = (str.charAt(start) ^ '0');
            if ( c > 9 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            out = (out << 1) + (out << 3) + c;
        }

        if ( c1 == '-' ){
            out = ~out + 1;
            if ( out > 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
            return out;
        }

        if ( out < 0 ) throw new NumberFormatException( String.format("Not a valid integer value. Input: '%s'.", str) );
        return out;
    }

    您可以使用parseint方法

    1
    2
    3
      String SrNumber="5790";
    int extractNumber = Integer.parseInt(SrNumber);
    System.out.println(extractNumber);//Result will be --5790

    用Java整数类的EDCOX1 12Ω方法将字符串转换为整数。parseInt方法是将字符串转换为int,如果字符串无法转换为int类型,则抛出NumberFormatException

    忽略它可能引发的异常,请使用以下命令:

    1
    int i = Integer.parseInt(myString);

    如果由变量EDCOX1 OR 28表示的字符串是一个有效的整数,如EDCOX1,29,那么它将被转换成Java int。如果它由于任何原因而失败,则该改变可以抛出EDCOX1×8,因此代码应该更长一点来解释这一点。

    Ex.JavaEDCX1〔17〕对EDCOX1〔11〕转换方法,对可能的EDCOX1〔8〕进行控制。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    public class JavaStringToIntExample
    {
      public static void main (String[] args)
      {
        // String s ="test";  // use this if you want to test the exception below
        String s ="1234";

        try
        {
          // the String to int conversion happens here
          int i = Integer.parseInt(s.trim());

          // print out the value after the conversion
          System.out.println("int i =" + i);
        }
        catch (NumberFormatException nfe)
        {
          System.out.println("NumberFormatException:" + nfe.getMessage());
        }
      }
    }

    如果更改尝试失败——如果您可以尝试将Java字符串测试转换为int -整数EDCOX1,则12进程将抛出EDCOX1字段8,您必须在TI/catch块中进行处理。


    使用Integer.parseInt(),这将帮助您将字符串值解析为int。

    例子:

    1
    2
    3
    String str ="2017";
    int i = Integer.parseInt(str);
    System.out.println(i);

    输出:二千零一十七


    自定义算法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    public static int toInt(String value) {
      int output = 0;
      boolean isFirstCharacter = true;
      boolean isNegativeNumber = false;
      byte bytes[] = value.getBytes();
      for (int i = 0; i < bytes.length; i++) {
        char c = (char) bytes[i];
        if (!Character.isDigit(c)) {
          isNegativeNumber = (c == '-');
          if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
            throw new NumberFormatException("For input string "" + value +""");
          }
        } else {
          int number = Character.getNumericValue(c);
          output = output * 10 + number;
        }
        isFirstCharacter = false;
      }
      if (isNegativeNumber) output *= -1;
      return output;
    }

    另一个解决方案:(使用字符串charat方法,而不是将字符串转换为字节数组):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public static int toInt(String value) {
      int output = 0;
      boolean isFirstCharacter = true;
      boolean isNegativeNumber = false;
      for (int i = 0; i < value.length(); i++) {
        char c = value.charAt(i);
        if (!Character.isDigit(c)) {
          isNegativeNumber = (c == '-');
          if (!(isFirstCharacter && (isNegativeNumber || c == '+'))) {
            throw new NumberFormatException("For input string "" + value +""");
          }
        } else {
          int number = Character.getNumericValue(c);
          output = output * 10 + number;
        }
        isFirstCharacter = false;
      }
      if (isNegativeNumber) output *= -1;
      return output;
    }

    实例:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    int number1 = toInt("20");
    int number2 = toInt("-20");
    int number3 = toInt("+20");
    System.out.println("Numbers =" + number1 +"," + number2 +"," + number3);

    try {
      toInt("20 Hadi");
    } catch (NumberFormatException e) {
      System.out.println("Error:" + e.getMessage());
    }

    使用String的不同输入尝试此代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    String a ="10";  
    String a ="10ssda";  
    String a = null;
    String a ="12102";

    if(null != a) {
        try {
            int x = Integer.ParseInt(a.trim());
            Integer y = Integer.valueOf(a.trim());
            //  It will throw a NumberFormatException in case of invalid string like ("10ssda" or"123 212") so, put this code into try catch
        } catch(NumberFormatException ex) {
            // ex.getMessage();
        }
    }

    或者,可以使用integer.valueof()。它将返回一个Integer对象。

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

    输出: