본문 바로가기
자료구조 | 알고리즘/문제

[JAVA] 문자열 - 대소문자 변환

by 동기 2022. 9. 23.
반응형

설명

대문자와 소문자가 같이 존재하는 문자열을 입력받아 대문자는 소문자로 소문자는 대문자로 변환하여 출력하는 프로그램을 작성하세요.

입력

첫 줄에 문자열이 입력된다. 문자열의 길이는 100을 넘지 않습니다.

문자열은 영어 알파벳으로만 구성되어 있습니다.

출력

첫 줄에 대문자는 소문자로, 소문자는 대문자로 변환된 문자열을 출력합니다.

예시 입력 1 

StuDY

예시 출력 1

sTUdy

 

풀이

대문자는 소문자로, 소문자는 대문자로 변환하는 것을 알아야 함!
Character 클래스를 이용하였습니다.

public class ToUpperToLower {
    public String solution(String sentence){
        StringBuilder answer = new StringBuilder();
        for(char x : sentence.toCharArray()){
            if(Character.isLowerCase(x))
                x = Character.toUpperCase(x);
            else
                x = Character.toLowerCase(x);
            answer.append(x);
        }
        return answer.toString();
    }
    public static void main(String[] args) {
        ToUpperToLower toUpperToLower = new ToUpperToLower();
        Scanner scan = new Scanner(System.in);
        String sentence = scan.next();
        System.out.println(toUpperToLower.solution(sentence));
    }
}

 

다른 풀이

ASCII code 를 이용한 풀이 방법도 있습니다

 

ASCII Code

a는 97, A는 65

소문자와 대문자와의 차이는 32가 납니다

public class ToUpperToLower {
    public String ASCIISolution(String sentence){
        StringBuilder answer = new StringBuilder();
        for(char x : sentence.toCharArray()){
            if(65<=x && x<=90)//대문자일 경우
                answer.append((char) (x + 32)); // 32를 더해줘서 소문자로 바꿔준다
            else
                answer.append((char) (x - 32)); // 아닌경우(소문자일경우) 32를 빼줘서 대문자로 바꿔준다
        }
        return answer.toString();
    }
    public static void main(String[] args) {
        ToUpperToLower toUpperToLower = new ToUpperToLower();
        Scanner scan = new Scanner(System.in);
        String sentence = scan.next();
        System.out.println(toUpperToLower.ASCIISolution(sentence));
    }
}

 

 

반응형

댓글