Programing

Java에서 문자열을 int로 변환하는 방법

c10106 2022. 5. 20. 21:27
반응형

Java에서 문자열을 int로 변환하는 방법

어떻게 변환할 수 있는가?String완전히int?

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

Java 문서를 보면 "캐치"라는 것이 이 함수가 다음을 발생될 수 있다는 것을 알 수 있을 것이다.NumberFormatException, 처리할 수 있는 항목:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
   foo = 0;
}

(이 치료는 다음과 같은 잘못된 형식의 숫자를 기본값으로 설정함0,하지만 원한다면 다른 것도 할 수 있다.)

또는 다음을 사용할 수 있다.Ints 의 구아바(Guava(Guava) Optional는 문자열을 int로 변환하는 강력하고 간결한 방법을 만든다.

import com.google.common.primitives.Ints;

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

예를 들어 다음과 같은 두 가지 방법이 있다.

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

이러한 방법에는 약간의 차이가 있다.

  • valueOf의 새 인스턴스 또는 캐시된 인스턴스 반환java.lang.Integer
  • parseInt원시적인 것으로 돌아오다.int.

모든 경우에 동일하다.Short.valueOf/parseShort Long.valueOf/parseLong

음, 고려해야 할 매우 중요한 점은 정수 파서가 숫자를 던진다는 것이다.자바독에 명시된 FormatException.

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

분할 인수의 정수 값을 가져오려고 하거나 어떤 것을 동적으로 구문 분석할 때 이 예외를 처리하는 것이 중요하다.

수동으로 수행:

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

대체 솔루션은 Apache Commons의 NumberUtils:

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

Apache 유틸리티는 문자열이 잘못된 숫자 형식이면 항상 0이 반환되기 때문에 좋다.그래서 시도 캐치 블록을 절약하는 겁니다.

Apache NumberUtils API 버전 3.4

Integer.decode

사용할 수도 있다.public static Integer decode(String nm) throws NumberFormatException.

8번 베이스와 16번 베이스에서도 작동한다.

// 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"); 
    
  2. intValue():

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

현재 나는 위의 것과 같은 특정 표현을 사용할 수 없는 대학 과제를 하고 있으며, ASCII 표를 보면서 겨우 그럭저럭 해냈다.훨씬 더 복잡한 코드지만 나처럼 제약이 있는 다른 사람들을 도울 수 있을 거야.

제일 먼저 해야 할 일은 입력을 받는 것, 이 경우에는 한 줄의 숫자로, 나는 그것을 부르지.String number이 경우에는 12라는 숫자를 사용해서 예를 들어볼게.String number = "12";

또 다른 한계점은 반복적인 사이클을 사용할 수 없다는 점이었다.for사이클(완벽했을 것)도 사용할 수 없다.이것은 우리를 약간 제한한다. 하지만 다시, 그것이 목표다.두 자리(마지막 두 자리)만 필요했기 때문에 간단한 것charAt해결:

 // 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);

코드가 있으면 표를 보고 필요한 사항을 조정하면 된다.

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

자, 왜 두 배로?음, 정말 이상한 발걸음 때문에.현재 복식 1, 2개가 있지만 12개로 바꿔야 해, 우리가 할 수 있는 수학 연산이 없어.

우리는 후자(마지막 자리)를 10으로 나누어 유행하고 있다.2/10 = 0.2(왜 이중인가) 이렇게 말한다.

 lastdigit = lastdigit / 10;

이것은 단지 숫자 놀이에 불과하다.우리는 마지막 숫자를 십진수로 바꾸고 있었다.하지만 이제, 무슨 일이 일어나는지 보십시오.

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

수학에 너무 몰입하지 않고, 우리는 단지 숫자의 숫자를 단위로 분리할 뿐이다.알다시피, 우리는 0-9만을 고려하기 때문에, 10의 배수로 나누는 것은 그것을 저장하는 "상자"를 만드는 것과 같다. (1학년 선생님이 단원과 백이 무엇인지 설명했을 때를 생각해 보라.)자:

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

여기 있어.다음과 같은 제한 사항을 고려하여 숫자 문자열(이 경우 두 자리)을 이 두 자리수로 구성된 정수로 변환한 경우:

  • 반복 주기 없음
  • 구문 분석과 같은 "마법" 표현 없음인트

이를 위한 방법:

  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.valueOfa를 생산하다.Integer사물과 다른 모든 방법. 원시 int.

마지막 두 가지 방법은 커먼스 랭3와 여기서의 전환에 관한 큰 기사에서 나온 것이다.

주어진 문자열에 정수(Instant)가 포함되어 있지 않을 가능성이 조금이라도 있을 때마다 이 특별한 경우를 처리해야 한다.안타깝게도 표준 자바 방식은Integer::parseInt그리고Integer::valueOfA를 던지다NumberFormatException으로 불량 따라서 일반적으로 불량 코딩 스타일로 간주되는 흐름 제어에는 예외를 사용해야 한다.

내 생각에는 이 특별한 사건은 빈칸을 반납하는 것으로 처리해야 한다.Optional<Integer>는 그런 에 나는 과 같은 자바에서는 그런 방법을 제공하지 않기 때문에 나는 다음과 같은 포장지를 사용한다.

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

사용 예:

// prints "12"
System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));
// prints "-1"
System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));
// prints "invalid"
System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));

이것은 여전히 내부 흐름 제어에 예외를 사용하고 있지만, 사용 코드는 매우 깨끗해진다.또, 어떤 경우에 해당하는지 명확하게 구분할 수 있다.-1유효한 값으로 구문 분석되며, 유효하지 않은 문자열을 구문 분석할 수 없는 경우.

사용하다.

다음 사항을 기억하십시오.

Integer.parseInt("1");// 확인

Integer.parseInt("-1");// 확인

Integer.parseInt("+1");// 확인

Integer.parseInt(" 1");)/ 예외(공백)

Integer.parseInt("2147483648");// 예외(Integer는 최대값 2,147,483,647로 제한됨)

Integer.parseInt("1.1");// 예외(. 또는 , 또는 허용되지 않는 모든 것)

Integer.parseInt("");// 예외(0 또는 기타 아님)

예외 유형은 하나뿐입니다.

문자열을 int로 변환하는 것은 단순히 숫자를 변환하는 것보다 더 복잡하다.다음과 같은 문제에 대해 생각해 보십시오.

  • 문자열에 숫자 0-9만 포함되어 있는가?
  • -/+는 문자열 전후에 어떻게 된 거야?그게 가능한가(회계번호 참조)?
  • MAX_-/MIN_INFINITY는 왜 그래?문자열이 99999999999999999999999999999이면 어떻게 되는가?기계가 이 끈을 인트로 취급할 수 있을까?

우리는 그것을 사용할 수 있다.parseInt(String str)Integer문자열 값을 정수 값으로 변환하기 위한 래퍼 클래스.

예를 들면 다음과 같다.

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

Integer클래스는 또한 다음을 제공한다.valueOf(String str)방법:

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

우리는 또한 사용할 수 있다.toInt(String strValue)변환을 위한 NumberUtils 유틸리티 클래스:

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

나는 해결책이 있지만 그것이 얼마나 효과적인지 모른다.하지만 그것은 잘 작동하고, 나는 네가 그것을 개선할 수 있다고 생각해.반면에, 나는 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));
        }
    }
}

Google GuavatryParse(스트링)를 가지고 있으며, 이를 반환한다.null문자열을 구문 분석할 수 없는 경우(예:

Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
  ...
}

숫자를 제외한 모든 문자를 제거한 다음 정수를 구문 분석하는 것으로 시작할 수도 있다.

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

그러나 이것은 음수가 아닌 숫자에만 효과가 있다는 것을 경고하라.

앞의 답변과는 별도로 몇 가지 기능을 추가하고자 한다.이러한 결과를 사용하는 동안 다음과 같이 하십시오.

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
}

구현:

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

언급했듯이 아파치 커먼즈'는 다음과 같다.NumberUtils할 수 있다돌아온다.0줄을 int로 변환할 수 없는 경우

자신의 기본값을 정의할 수도 있다.

NumberUtils.toInt(String str, int defaultValue)

예:

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: 메시지 대화 상자를 표시하는 등 예외를 명시적으로 처리한 다음 현재 워크플로우의 실행을 중지하십시오.예를 들면 다음과 같다.

    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 (NumberFormatException ex) {
        integerValue = 0;
    }
    

상수는 null 값을 반환하지 않기 때문에, 비교나 어떤 종류의 컴퓨팅에 문자열 상수를 사용하는 것은 항상 좋은 생각이다.

사용할 수 있다new Scanner("1244").nextInt(). 또는 int가 존재하는지 물어 보십시오.new Scanner("1244").hasNextInt()

프로그래밍 경기에서는 숫자가 항상 유효한 정수가 될 것이라고 확신하는 경우, 입력 내용을 구문 분석하는 고유한 방법을 작성할 수 있다.이렇게 하면 모든 유효성 검사 관련 코드를 건너뛰고(이 중 어느 것도 필요하지 않기 때문에) 효율성이 약간 높아질 것이다.

  1. 유효한 양의 정수인 경우:

    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;
    }
    
  2. 양의 정수 및 음의 정수 모두:

    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;
    }
    
  3. 이 숫자 앞이나 뒤에 공백이 있을 것으로 예상되면 다음 작업을 수행하십시오.str = str.trim()더 진행하기 전에

간단히 이것을 시도해 볼 수 있다.

  • 사용하다Integer.parseInt(your_string);a를 개종하다Stringint
  • 사용하다Double.parseDouble(your_string);a를 개종하다Stringdouble

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55

일반 문자열의 경우:

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

String Builder 및 String 버퍼의 경우 다음을 사용할 수 있다.

Integer.parseInt(myBuilderOrBuffer.toString());

스트링을 매개 변수로 삼는 정수 생성자를 아무도 언급하지 않았다는 사실이 조금 놀랍다.

자, 여기 있다:

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

Java 8 - 정수(String).

물론 시공자는 유형을 반환할 것이다.Integer, 그리고 박스 해제 연산은 값을 다음으로 변환한다.int.


참고 1: 다음을 언급하는 것이 중요하다.이 생성자는parseInt방법의

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

참고 2:이상 사용되지 않음:@Deprecated(since="9")- JavaDoc.

.parseInt()에 .try...catch예를 들어, 비반복 문자를 입력할 경우 오류를 처리하는 블록

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\n" + e.toString,
         "Error",
         JOptionPane.ERROR_MESSAGE);
    }
 }

다음과 같은 7가지 방법으로 수행할 수 있다.

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

String number = "999";
  1. Ints.tryParse:

    int 결과 = Ints.tryParse(숫자);

  2. NumberUtils.createInteger:

    정수 결과 = NumberUtils.create정수(숫자);

  3. NumberUtils.toInt:

    int 결과 = NumberUtils.toInt(숫자);

  4. Integer.valueOf:

    정수 결과 = 정수.값Of(숫자);

  5. Integer.parseInt:

    int 결과 = 정수.parseInt(숫자);

  6. Integer.decode:

    int 결과 = 정수.decode(숫자);

  7. Integer.parseUnsignedInt:

    int 결과 = 정수.parseUnsignedInt(숫자);

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

문자열에 숫자가 아닌 데이터가 없는지 확인하십시오.

자, 간다.

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

이것은 도서관을 이용하지 않고 모든 조건을 긍정적이고 부정적으로 하는 완전한 프로그램이다.

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

한 가지 방법은 파스인트(String)이다.원초적인 int를 반환한다.

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

두 번째 방법은 valueOf(String)이며, 새 Integer() 객체를 반환한다.

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
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);
    }
}

참조URL: https://stackoverflow.com/questions/5585779/how-do-i-convert-a-string-to-an-int-in-java

반응형