문장이 주어졌을 때, 단어를 모두 뒤집어서 출력하는 프로그램을 작성하시오. 단, 단어의 순서는 바꿀 수 없다. 단어는 영어 알파벳으로만 이루어져 있다.
첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 문장이 하나 주어진다. 단어의 길이는 최대 20, 문장의 길이는 최대 1000이다. 단어와 단어 사이에는 공백이 하나 있다.
각 테스트 케이스에 대해서, 입력으로 주어진 문장의 단어를 모두 뒤집어 출력한다.
2
I am happy today
We want to win the first prize
I ma yppah yadot
eW tnaw ot niw eht tsrif ezirp
//---- 세팅 ----//
const fs = require('fs');
const stdin = (
process.platform === 'linux'
? fs.readFileSync('/dev/stdin').toString()
: `\
2
I am happy today
We want to win the first prize
`
).split('\n');
const input = (() => {
let line = 0;
return () => stdin[line++];
})();
//---- 풀이 -----//
const t = Number(input());
const strArr = [];
[...Array(t)].forEach(() => {
strArr.push(input());
});
const reverseStr = str => str.split('').reverse().join('');
strArr.forEach(str => {
console.log(
str
.split(' ')
.map(word => reverseStr(word))
.join(' ')
);
});
strArr
라는 배열에 문장 1줄씩 원소로 담는다.
reverseStr
라는 단어를 뒤집는 함수를 구현한다.
strArr
을 순회하면서 단어별로 쪼개고 단어를 뒤집어 다시 원래대로 합쳐놓는다.