대문자로 통일

지창언·2022년 7월 24일

codingTest

목록 보기
11/29

Index

1.문제
2.내 코드
3.발전시킨 코드


문제

문자열을 입력받아, 문자열 전체를 대문자로 출력하시오.
예시)
입력 : "Music is my life"
출력 : "MUSIC IS MY LIFE"


내 코드

<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){         
                let answer ='';
                for(let i=0; i<s.length; i++){
                    if(s.charCodeAt(i)<91){
                        answer +=s[i];
                    }else{
                        answer +=String.fromCharCode(s.charCodeAt(i)-32);
                    }
                }
                return answer ;
            }
            let str="ItisTimeToStudy";
            console.log(solution(str));
        </script>
    </body>
</html>

ASCII 코드를 활용한 방법.
소문자의 ascii code - 32 = 대문자의 ascii code 임을 활용하자.


발전시킨 코드

<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){         
                let answer ='';
                for(let character of s){
                    answer += character.toUpperCase();
                }
                return answer ;
            }
            let str="ItisTimeToStudy";
            console.log(solution(str));
        </script>
    </body>
</html>

toUpperCase()함수를 활용하여 간소화 하는 방법.


profile
프론트엔드 개발자가 되고 싶은...

0개의 댓글