대문자찾기

지창언·2022년 7월 24일

codingTest

목록 보기
2/29

Index
1.문제
2.내 풀이
3.효율적 풀이


문제

입력받은 문자열에서 대문자를 찾아 그 갯수를 반환하시오.


바로 풀어본 코드

<!-- 65~90 : 대문자 알파벳-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){         
                let count =0;
                for(let i=0;i<s.length;i++){
                    if(s.charCodeAt(i)<=90 && s.charCodeAt(i)>=65){
                        count ++;
                    }
                }
                return count;
            }

            let str="KoreaTimeGood";
            console.log(solution(str));
        </script>
    </body>
</html>

위는 문제를 처음 보고 생각해낸 코드를 바로 작성한 것이다.
문자열에서 문자를 하나씩 검사해, 해당 문자의 ASCII 코드 값을 통해 대문자(65~90)를 판별하고자 하였다.(아래 아스키 코드 표 참조)


출처 : https://img1.daumcdn.net/thumb/R1280x0/?scode=mtistory2&fname=http%3A%2F%2Fcfile5.uf.tistory.com%2Fimage%2F216CE84C52694FF02054D4


향상된 code

아래는 좀 더 직관적인 코드 풀이이다.

<!-- 65~90 : 대문자 알파벳-->
<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){         
                let count =0;
                for(x of s){
                    if(x ===x.toUpperCase()) count++;
                }
                return count;
            }
            let str="KoreaTimeGood";
            console.log(solution(str));
        </script>
    </body>
</html>

toUpperCase() 메서드를 통해 대문자 판별을 쉽게 하였다.
적절한 메서드를 떠올리는 것이 코드 간소화에 중요하다 !

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

0개의 댓글