如何将String转换为int?

"1234"  →  1234

当前回答

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

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

其他回答

嗯,需要考虑的一个非常重要的点是Integer解析器抛出了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.
}

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

使用此方法可以避免错误。

String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};

也可以从删除所有非数字字符开始,然后解析整数:

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

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

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

可以使用Integer.parseInt():字符串测试=“4568”;int new=Integer.parseInt(测试);也可以使用Integer.valueOf():字符串测试=“4568”;int new=Integer.valueOf(测试);

自定义算法:

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

另一种解决方案:

(使用string charAt方法,而不是将字符串转换为字节数组)

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

示例:

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