문제 설명

영문자 대/소문자로 이루어진 문자열 s가 주어집니다.

이 문자열의 대/소문자를 서로 뒤집는 프로그램을 구현하세요.


입력 형식

· s : 영문자 대/소문자로 이루어진 문자열


출력 형식

· 대/소문자를 뒤집은 결과를 문자열로 반환


제약 사항

· 0 <= s.length <= 100


입출력 예시

· 예시1

      · s = "Naver"

      · 출력 : "nAVER"

      · 설명 : 대문자 N은 소문자로, 나머지는 대문자로 변환하면 된다.


작성 코드

class Solution {
    public String solution(String s) {

        StringBuilder st = new StringBuilder(s.length());

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isUpperCase(c)) { // 대문자면
                st.append(Character.toLowerCase(c)); // 소문자로 바꿔서 추가
            } else if (Character.isLowerCase(c)) { // 소문자면
                st.append(Character.toUpperCase(c)); // 대문자로 바꿔서 추가
            }
        }
        return st.toString(); // StringBuilder 객체를 String 객체로 변환하여 리턴한다.
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        String s = "Naver";
        System.out.println(st.solution(s));
    }
}

 

정답 코드

class Solution {
    public String solution(String s) {
        StringBuilder sb = new StringBuilder();
        for (char c: s.toCharArray()) {
            if ('a' <= c && c <= 'z') {
                c = (char)(c - 'a' + 'A');
            } else {
                c = (char)(c - 'A' + 'a');
            }
            sb.append(c);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Solution st = new Solution();
        String s = "Naver";
        System.out.println(st.solution(s));
    }
}