Как мне преобразовать строку в int в Java? - PullRequest
2805 голосов
/ 07 апреля 2011

Как я могу преобразовать String в int в Java?

Моя строка содержит только числа, и я хочу вернуть число, которое она представляет.

Например,учитывая строку "1234", результатом должно быть число 1234.

Ответы [ 43 ]

3 голосов
/ 21 июня 2018

Кстати, учтите, что если строка пуста, вызов:

int i = Integer.parseInt(null);

создает исключение NumberFormatException, а не NullPointerException.

2 голосов
/ 27 июля 2018

public static int parseInt (String s) генерирует 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";// throwns NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

public static Integer valueOf (String s) генерирует 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/

2 голосов
/ 25 декабря 2018
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);
    }
}
1 голос
/ 29 ноября 2018

Integer.parseInt(myString); - с использованием класса оболочки

1 голос
/ 09 ноября 2018

Преобразование строки в целое число с помощью метода parseInt класса Java Integer.Метод parseInt заключается в преобразовании строки в целое число и выдает 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.

0 голосов
/ 18 февраля 2019

Используйте этот метод:

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;
}
0 голосов
/ 06 февраля 2019

Некоторые из способов преобразования String в Int следующие:

  1. вы можете использовать Integer.parseInt():

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

  2. также вы можете использовать Integer.valueOf():

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

0 голосов
/ 21 января 2019

Я написал этот быстрый метод для разбора ввода строки в int или long. Это быстрее, чем текущий JDK 11 Integer.parseInt или Long.parseLong. Хотя вы спрашивали только int, я также включил длинный парсер. Парсер кода ниже требует, чтобы метод парсера был маленьким, чтобы он мог работать быстро. Альтернативная версия находится под тестовым кодом. Альтернативная версия довольно быстрая и не зависит от размера класса.

Этот класс проверяет наличие переполнения, и вы можете настроить код в соответствии с вашими потребностями. Пустая строка будет давать 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, 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;
}
0 голосов
/ 14 января 2019

Вы можете использовать Integer.parseInt() метод

Пример:

String strNumber = "5790";
int extractNumber = Integer.parseInt(strNumber);

//Result will be --5790
System.out.println(extractNumber);

0 голосов
/ 22 августа 2018

Используйте Integer.parseInt(), это поможет вам разобрать строковое значение в int.

Пример:

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

Выход: 2017

...