본문 바로가기

프로그래밍/코딩테스트

[프로그래머스] lv0. 대소문자 변경하여 출력하기

https://school.programmers.co.kr/learn/courses/30/lessons/181949

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

영어 문자 str이 주어지면 소문자 -> 대문자, 대문자 -> 소문자로 각각 변경하여 출력하는 문제이다.

 

제약조건은 str의 길이가 1이상 20이하 이며 str은 알파벳으로 이루어져있다.

Scanner의 input value는 aBcDeFg가 주어졌다

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        String result = "";
        
        for (int i =0;  i < a.length(); i++){
            char word = a.charAt(i);
            
            if(Character.isLowerCase(word)){
                result += Character.toUpperCase(word);
            }else {
                result += Character.toLowerCase(word);
            }    
        }
          System.out.print(result);   
    }
}

그리하여 char 자료형인 word객체에다가 for문을 활용하여 input 값을 한단어씩 넣고 if문에 Character.isLowerCase()를 활용하였다.

isLowerCase()는 boolean값을 return하는 함수로 소문자인경우에는 result라는 String 객체에 toUppserCase()함수를 사용한 값을 반복적으로 넣는 형태로 마무리된다. 그 후 for문이 종료되면 result에 담았던 문자열이 출력되게 하는 방식이다.

 

다른분의 문제풀이

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.next();
        for(int i=0; i<a.length(); i++) {
            char c = a.charAt(i);
            if(Character.isUpperCase(c)) {
                System.out.print((char)(c+32));
            }
            else {
                System.out.print((char)(c-32));
            }
        }
    }
}

아스키코드를 활용하여 대문자에는 32를 더하여 소문자로 만들고 소문자인경우에는 32를 빼서 대문자로 변경하여 출력하게 한 모습이었다

 

교육과정중 선생님께서 자료구조중에 가장 기본이라고 하셨던 아스키코드도 활용할수있구나. 그리고 앞선 문자열 출력과마찬가지로 for문을 돌려서 String객체에 넣는것이 아니라 StringBuilder에 넣어서 문제풀이를 했어야했는데 놓치고 있지않았나 라는 생각을 하게되었다.