BackEnd/JAVA

[JAVA] Char type to Integer type 주의할 점!

hwa2 2022. 7. 5. 00:25

코딩테스트 공부를 하던 도중 Character타입을 Integer로 변환할 때 원했던 숫자가 아닌 아스키 코드로 출력된다는 것을 발견했다!!

평소에 Character타입을 많이 사용할 일이 없다보니 새롭게 알게 된 사실! (기억해둡시다.)

 

String to Integer

Integer.valueOf(s);
Integer.parseInt(s);
String을 Integer로 바꿀 때는 Integer에서 지원하는 함수로 쉽게 String 내의 숫자를 얻을 수 있다.

 

Char to Integer - Ascii code??

그러나 Char타입을 Integer로 변환 할 때는 Ascii code로 결과값이 반환된다.
왜일까?
(보충)

 

이처럼 아래 방법을 사용하여 변환하면 Char타입 c의 숫자 값을 아스키코드로 반환하게 된다.
Integer.valueOf(c);
(int)c;

위 방법을 이용해 변환하면 Char타입 c의 숫자 값을 아스키코드로 변환하게 된다.

 

그렇다면 Char 타입의 숫자를 그대로 정수 Integer로 어떻게 변환할 수 있을까?

  • Character에서 지원하는 getNumbericValue()함수를 사용한다.
    ⁠Chracter.getNumericValue(c);
  • Char값에서 0의 아스키코드를 뺀다.
    c-'0'
    위처럼 기존 Character값의 숫자 아스키코드에서 0의 아스키코드를 빼면 그 차이만큼의 숫자 값이 나오게 된다.

 

<예시코드>

public static void main(String[] args) {
        char c = '5';
        String s = "5";

        System.out.println(s);  //5
        System.out.println(c);  //5

        // String to Integer -> 원했던 숫자 출력
        System.out.println(Integer.valueOf(s));   //5
        System.out.println(Integer.parseInt(s));  //5

        // char to Integer -> 아스키 코드 출력
        System.out.println(c-0);    //53
        System.out.println(Integer.valueOf(c)); //53
        System.out.println((int)c); //53

        // char to Integer -> 원했던 숫자 출력
        System.out.println(Character.getNumericValue(c));   //5
        System.out.println(c-'0');  //5 -> c의 값 5의 아스키코드 53에서 0의 아스키 코드 48을 뺀 결과 원했던 값 5가 나온다.
    }