입력받은 문자열에서 대문자를 찾아 그 갯수를 반환하시오.
<!-- 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)를 판별하고자 하였다.(아래 아스키 코드 표 참조)
아래는 좀 더 직관적인 코드 풀이이다.
<!-- 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() 메서드를 통해 대문자 판별을 쉽게 하였다.
적절한 메서드를 떠올리는 것이 코드 간소화에 중요하다 !