Coding Test/Programmers
[프로그래머스/JavaScript] 코딩 테스트 풀이 (문제 43 - 대문자와 소문자)
dev-ini
2024. 2. 10. 15:44
728x90
# 문제
문자열 my_string이 매개변수로 주어질 때, 대문자는 소문자로 소문자는 대문자로 변환한 문자열을 return하도록 solution 함수를 완성해주세요.
# 답안
// 방법1) for 반복문 사용
function solution(my_string) {
let str = "";
for (let i = 0; i < my_string.length; i++) {
if (my_string[i] === my_string[i].toUpperCase()) {
str += my_string[i].toLowerCase();
} else {
str += my_string[i].toUpperCase();
}
}
}
return str;
}
// 방법2) for...of 반복문 사용
function solution(my_string) {
let answer = "";
for (let i of my_string) {
if (i === i.toUpperCase()) {
answer += i.toLowerCase();
} else {
answer += i.toUpperCase();
}
}
return answer;
}
// 방법 3) split, map, join 사용
function solution(my_string) {
return my_string.split('').map(n => n === n.toUpperCase() ? n.toLowerCase() : n.toUpperCase()).join('')
}
# 인사이트
// 대문자 만들기는 toUpperCase()
// 소문자 만들기는 toLowerCase()
728x90