영어 알파벳으로 이루어진 문자열 str이 주어집니다. 각 알파벳을 대문자는 소문자로 소문자는 대문자로 변환해서 출력하는 코드를 작성해 보세요.
제한사항
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function (line) {
input = [line];
}).on('close',function(){
str = input[0];
let split = str.split('');
let result = [];
for (let i of split) {
if (i.charCodeAt() >= 65 && i.charCodeAt() <= 90) {
// 대문자일 경우
result.push(i.toLowerCase());
} else {
// 소문자일 경우
result.push(i.toUpperCase());
}
}
console.log(result.join(''));
});
뭔가 엄청 복잡하게 풀어버렸음…
split 변수에 str를 배열로 쪼개어 할당하고, 결과를 담을 result라는 빈 배열을 선한다.
for문을 통해 split의 배열을 하나씩 돌아준다.
각각의 원소를 아스키코드로 변환해서 대문자와 소문자를 구분한 후, 대문자일 경우 toLowerCase()를 통해서 소문자로 바꿔주고, 소문자일 경우 toUpperCase()를 통해서 대문자로 바꿔준다.
이후 result 배열에 담긴 원소들을 join() 메서드를 통해 문자열로 합친 후 결과를 반환한다.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function (line) {
input = [line];
}).on('close',function(){
str = input[0];
// map() 함수로 각 문자에 대해 대소문자 변환을 한 뒤, join('')으로 문자열로 합침
const result = str.split('').map(char =>
char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()
).join('');
console.log(result);
});
split() 함수를 통해 str를 배열로 쪼개고, map() 함수를 통해 배열을 변환해준다.
삼항연산자를 통해 각 문자(char)가 toUpperCase()를 해준 값과 같다면(true)?! 대문자라는 이야기니까 소문자로 변환해주고, 반대의 경우 (false) 대문자로 변화한다. 그리고 join() 메서드를 통해 문자열로 합쳐준 후 반환해준다.
아… 아스키코드로 복잡하게 if 조건을 걸 필요 없이! 메서드를 이용해서 판별할 수 있다! 오!
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = [];
rl.on('line', function (line) {
input = [line];
}).on('close',function(){
str = input[0].split('');
str.forEach((value, index) => {
if (value === value.toUpperCase()) {
str[index] = value.toLowerCase();
} else {
str[index] = value.toUpperCase();
}
});
console.log(str.join(''));
});
아스키코드만 골똘히 생각하고 있었는데, 이런 식으로 바꿔주는 방법이 있다는 것을 배웠다! 와~