如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
将字符串转换为int比仅转换数字更复杂。您已经考虑了以下问题:
字符串是否只包含数字0-9?字符串之前或之后的-/+怎么了?这是可能的吗(指会计数字)?MAX_-/MIN_INFINITY怎么了?如果字符串为99999999999999999999,会发生什么?机器可以将此字符串视为int吗?
其他回答
我们可以使用Integer包装器类的parseInt(Stringstr)方法将String值转换为整数值。
例如:
String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);
Integer类还提供了valueOf(Stringstr)方法:
String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);
我们还可以使用NumberUtils实用程序类的toInt(StringstrValue)进行转换:
String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
使用Java integer类的parseInt方法将字符串转换为整数。parseInt方法将字符串转换为int,如果字符串无法转换为int类型,则抛出NumberFormatException。
忽略它可能引发的异常,请使用以下命令:
int i = Integer.parseInt(myString);
如果变量myString表示的字符串是有效的整数,如“1234”、“200”、“1”,它将被转换为Java int。如果由于任何原因失败,则更改可能引发NumberFormatException,因此代码应该稍长一些才能解释这一点。
例如,Java String到int的转换方法,控制可能的NumberFormatException
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 String测试转换为int),Integer parseInt进程将抛出NumberFormatException,您必须在try/catch块中处理该异常。
我编写了这个快速方法来将字符串输入解析为int或long。它比当前的JDK 11 Integer.parseInt或Long.parseLong更快。虽然您只要求int,但我也包含了Long解析器。下面的代码解析器要求解析器的方法必须很小才能快速运行。测试代码下面是另一个版本。另一个版本非常快,它不依赖于类的大小。
此类检查溢出,您可以自定义代码以适应您的需要。空字符串将使用我的方法生成0,但这是故意的。你可以改变它以适应你的情况或按原样使用。
这只是类中需要parseInt和parseLong的部分。注意,这只处理基数为10的数字。
int解析器的测试代码在下面的代码下面。
/*
* 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 - kevin@fai.host.
**/
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秒左右。
// 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的数学优化。
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. It 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;
}
例如,这里有两种方法:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
这些方法略有不同:
valueOf返回java.lang.Integer的新实例或缓存实例parseInt返回基元int。
所有情况都是一样的:Short.valueOf/parseShort、Long.valueOf/parseLong等。
您也可以使用此代码,但要注意一些事项。
选项#1:显式处理异常,例如,显示消息对话框,然后停止当前工作流的执行。例如:尝试{字符串字符串值=“1234”;//从字符串到整数int integerValue=Integer.valueOf(stringValue);//或int整数值=整数.ParseInt(字符串值);//现在从整数返回字符串stringValue=String.valueOf(整数值);}catch(NumberFormatException ex){//JOptionPane.showMessageDialog(帧,“无效输入字符串!”);System.out.println(“输入字符串无效!”);回来}选项#2:如果发生异常,执行流可以继续,则重置受影响的变量。例如,在catch块中进行了一些修改catch(NumberFormatException ex){整数值=0;}
使用字符串常量进行比较或任何类型的计算总是一个好主意,因为常量永远不会返回空值。