JS 알고리즘 문제풀이/섹션 1. 기본문제 풀이
12.대문자로 통일
crab.
2022. 1. 12. 11:30
반응형
📌강의 정리
대문자는 그대로 두고 소문자를 찾으면 대문자로 바꿔준다.
우선 let x of s로 하나씩 찾는다 이때 if문을 사용한다.
소문자로 바꿔주는 것은 toLowerCase()이므로 문자 하나씩 소문자로 바꿔줘서 비교하는 조건문을 걸어준다.
이때 정답 문자열에 += 연산자를 써서 하나씩 넣어주면 된다.
ascii코드로도 풀 수 있다. num값을 charCodeAt()으로 아스키로 넣어준후
97, 122로 비교하여 소문자 찾고 ascii값에서 32를 빼어 대문자로 바꿔주면 된다.
이제 이 숫자를 다시 문자로 바꿔줘야 한다.
String.fromCharCode(num-32) 이다.
📌느낀점
11번 문제의 연장선상에 있는 문제이다.
대문자가 소문자로 바뀌는 코드가 toLowerCase()라는 것과
ascii코드 숫자를 문자로 바꾸는게 String.fromCharCode(num-32)라는 것을
잘알아둬야겠다. 저번 그리고 이번 문제로 문자열 관련하여 알고있는 메서드를 잘 기억해두자.
또한 문자열에 값을 추가할때는 아주 간단하게 +를 쓰면된다는 것도 기억해두자.
//나의 코드
<html>
<head>
<meta charset="UTF-8">
<title>출력결과</title>
</head>
<body>
<script>
function solution(s){
let answer="";
for(let x of s){
console.log(x.toUpperCase());
answer = answer + x.toUpperCase();
}
return answer;
}
let str="ItisTimeToStudy";
console.log(solution(str));
</script>
</body>
</html>
//강사님 코드
<html>
<head>
<meta charset="UTF-8">
<title>출력결과</title>
</head>
<body>
<script>
function solution(s){
let answer="";
for(let x of s){
let num=x.charCodeAt();
if(num>=97 && num<=122) answer+=String.fromCharCode(num-32);
else answer+=x;
//if(x===x.toLowerCase()) answer+=x.toUpperCase();
//else answer+=x;
}
return answer;
}
let str="ItisTimeToStudy";
console.log(solution(str));
</script>
</body>
</html>
반응형