대소문자 바꿔서 출력하기

이리·2024년 7월 29일
0

문제 (프로그래머스 181949번 : 대소문자 바꿔서 출력하기)
181949 : 대소문자 바꿔서 출력하기

영어 알파벳으로 이루어진 문자열 str이 주어집니다. 각 알파벳을 대문자는 소문자로 소문자는 대문자로 변환해서 출력하는 코드를 작성해 보세요.

문제파악

  • 넘겨진 파라미터 : x
  • 알파벳으로 이루어진 문자열 str을 character 하나씩 보면서 대 소문자를 변경해야한다.

접근방법

  • 문자열 str을 character로 하나씩 쪼개서 살펴볼 것 : str.charAt(index)로 접근 가능
  • ASCII 코드로 접근할 생각인데.. 대문자 + 32 = 소문자 / 소문자 - 32 = 대문자 활용
  • ArrayList에 결과물을 add해서 최종 출력

코드구현

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        List<Character> answer = new ArrayList<>();
        
        for(int i = 0; i < a.length(); i++){
            char c = a.charAt(i);
            // 대문자일 경우 >> 소문자로 변환
            if(c >= 'A' && c <= 'Z'){
                c = (char)(c + 32);
            }
            
            // 소문자일 경우 >> 대문자로 변환
            else if(c >= 'a' && c <= 'z'){
                c = (char)(c - 32);
            }
            
            answer.add(c);
        }
        
        // 결과 출력
        for (char ch : answer) {
            System.out.print(ch);
        }
        System.out.println();  // 마지막 줄 바꿈
    }
}

배운점

  1. 문자열을 character 하나씩 뜯어보는 방법 : charAt
    for(int i = 0 ; i < str.length() ; i++){
    	str.charAt(i); // 0~str.length()까지 character 별로 하나씩 순회
    }
    String, char 간의 변환은 다음에 다시 공부하도록 하자..
  2. ArrayList를 출력하는 방법
    System.out.print(answer) 
    // >> 출력 : [A, b, C, d, E, f, G]
    형태로 배열을 출력하게 된다. ⇒ 배열의 요소를 하나씩 뽑아야한다!
    for (char ch : answer) {
              System.out.print(ch);
          }
          System.out.println();
    // >> 출력 : AbCdEfG
profile
Bonjour!

0개의 댓글