대소문자 변환

아기코딩단2·2022년 7월 27일
0

대소문자 변환
대문자와 소문자가 같이 존재하는 문자열을 입력받아 대문자는 소문자로 소문자는 대문자로
변환하여 출력하는 프로그램을 작성하세요.
▣ 입력설명
첫 줄에 문자열이 입력된다. 문자열의 길이는 100을 넘지 않습니다.
▣ 출력설명
첫 줄에 대문자는 소문자로, 소문자는 대문자로 변환된 문자열을 출력합니다.
▣ 입력예제 1
StuDY
▣ 출력예제 1
sTUdy

<!--my solution-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과 - 섹션1 - 13 - 대소문자 변환</title>
    </head>
    <body>
        <script>
            function solution(str) {
                let answer = "";
                for (char of str) {
                    if (char === char.toUpperCase()) {
                        answer += char.toLowerCase();
                    } else {
                        answer += char.toUpperCase();
                    }             
                } return answer;
            }
            let str = "BanAna";
            console.log(solution(str));
        </script>
    </body>
</html>

대문자로 바뀌면 char를 answer에 소문자로 넣고 아니면 대문자로 넣는다.

ex) Ban들어온다고 하면 B가 if 문으로 들어왔을 때 char.toUpperCase()니까 answer에는 toUpperCase()로 변환해서 넣어주면 된다.


<!--teacher's solution-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){  
                let answer="";
                for(let x of s){
                    if(x===x.toUpperCase()) answer+=x.toLowerCase();
                    else answer+=x.toUpperCase();
                }
                return answer;
            }

            console.log(solution("StuDY"));
        </script>
    </body>
</html>

코드는 똑같다 if 문 뒤에 문장이 하나면 괄호를 안쳐주고 else문도 괄호가 하나면 안쳐주고 그 차이다.

profile
레거시 학살자

0개의 댓글