[algorithm] 대문자 찾기

Ho-eng·2023년 4월 8일
0

❓ 대문자 찾기


한 개의 문자열을 입력받아 해당 문자열에 알파벳 대문자가 몇 개 있는지 알아내는 프로그램을 작성하세요.

  • 입력설명

    첫 줄에 문자열이 입력된다. 문자열의 길이는 100을 넘지 않습니다.

  • 출력설명

    첫 줄에 대문자의 개수를 출력한다.

  • 입력예제 1

    KoreaTimeGood

  • 출력예제 1

    3


❗ 문제 풀이

내 풀이

<html>
  <head>
    <meta charset="UTF-8" />
    <title>출력결과</title>
  </head>
  <body>
    <script>
      function solution(str) {
        let arr = []
        let strSplit = str.split("")

        strSplit.forEach((item) => {
          if (item === item.toUpperCase()) {
            arr.push(item)
          }
        })

        return arr.length
      }

      let str = "KoreaTimeGood"
      console.log(solution(str))
    </script>
  </body>
</html>
  1. arr이라는 빈배열과, 비교해야할 str을 한글자씩 쪼개서 배열로 넣어둔 strSplit을 선언한다.
  2. 순환을 돌면서 대문자인 경우, 빈 배열(arr)에 strSplit[i]를 넣는다.
  3. arr.length를 return한다.

정답 소스

<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){         
                let answer=0;
                for(let x of s){
                    //let num=x.charCodeAt();
                    //if(num>=65 && num<=90) answer++;
                    if(x===x.toUpperCase()) answer++; 
                }

                return answer;
            }

            let str="KoreaTimeGood";
            console.log(solution(str));
        </script>
    </body>
</html>
  1. 초기값 0인 answer라는 변수를 선언한다
  2. for of를 통해 대문자인경우 answer에 숫자 1씩 더해준다
profile
매일 '어제의 나와 오늘의 나는 무엇이 다를까?'를 고민하는 김호엥입니다.

0개의 댓글