如何将String转换为int?

"1234"  →  1234

当前回答

如果需要原语,请使用parseInt,否则使用Integer.valueOf()

其他回答

有多种方法可以将字符串int值转换为Integer数据类型值。您需要处理字符串值问题的NumberFormatException。

整数.分析Intfoo=整数.parseInt(myString);整数值foo=Integer.valueOf(myString);使用Java 8可选APIfoo=可选.Nullable(myString).map(整数::parseInt).get();

我有一个解决方案,但我不知道它有多有效。但它工作得很好,我认为你可以改进它。另一方面,我用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));
        }
    }
}

可以通过七种方式实现:

import com.google.common.primitives.Ints;
import org.apache.commons.lang.math.NumberUtils;

String number = "999";

Ints.tryParse:int result=Ints.tryParse(数字);NumberUtils.createInteger:整数结果=NumberUtils.createInteger(数字);应用到内部的数字:int result=NumberUtils.toInt(数字);整数值:整数结果=Integer.valueOf(数字);整数.分析整数:int result=Integer.parseInt(数字);整数代码:int result=Integer.decode(数字);整数.分析未签名:int result=Integer.parseUnsignedInt(数字);

公共静态int parseInt(字符串)引发NumberFormatException

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

将字符串“20”转换为原始int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

输出-20

如果字符串不包含可解析的整数,则将引发NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

公共静态Integer valueOf(字符串)引发NumberFormatException

您可以使用Integer.valueOf()。在这种情况下,它将返回一个Integer对象。

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

输出-20

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

我编写了这个快速方法来将字符串输入解析为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;
}