📢 문제 설명
문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하세요.
⛔ 제한 사항
문자열 전체의 짝/홀수 인덱스가 아니라, 단어(공백을 기준)별로 짝/홀수 인덱스를 판단해야합니다.
첫 번째 글자는 0번째 인덱스로 보아 짝수번째 알파벳으로 처리해야 합니다.
const s = "try hello world";
function solution(s) {
let answer = "";
const words = s.split(" "); // 문자열 > 배열로 단어들을 띄어쓰기를 기준으로 배열로 만들기
let arr = [];
for (let i = 0; i < words.length; i++) {
const word = Array.from(words[i]); //단어를 쪼개서 담는 배열이 필요하지 이건 데이터가 변하지 않을때니까 const
let convertWord = ""; // 하단에서 바뀌는 단어를 담는 곳
let convertSpellingArray = [];
for (let j = 0; j < word.length; j++) {
let spelling = word[j];
let convertSpelling =
j % 2 === 0 ? spelling.toUpperCase() : spelling.toLowerCase();
convertSpellingArray.push(convertSpelling);
}
convertWord = convertSpellingArray.join("");
arr.push(convertWord);
}
answer = arr.join(" ");
return answer;
}
function solution(s) {
s.split(" ")
.map((item) =>
Array.from(item)
.map((jtem, index) =>
index % 2 == 0 ? jtem.toUpperCase() : jtem.toLowerCase()
)
.join("")
)
.join(" ");
}
map() 으로 문장 > 단어 > 글자 순으로 변경하고 join()으로 합쳐줌
for문이랑 시간을 비교해봤을 때는 차이가 별로 없지만, 짧고 간결한건 이 코드가 맞는듯
function toWeirdCase2(s) {
var result = "";
var num = 0;
for (var i = 0; i < s.length; i++) {
if (s.charAt(i) == " ") {
num = 0;
result += " ";
continue;
} else if (num % 2 == 0) {
result += s.charAt(i).toUpperCase();
num++;
} else {
result += s.charAt(i).toLowerCase();
num++;
}
}
return result;
}
console.log(toWeirdCase2("try hello world"));
📌
chatAt()
str.charAt(index)
문자열에서 특정 인덱스에 위치하는 유니코드 단일 문자를 반환함
function toWeirdCase(s) {
let result = "";
for (let word of s.split(" ")) {
for (let i in word) {
result +=
word[i][parseInt(i) % 2 === 0 ? "toUpperCase" : "toLowerCase"]();
}
result += " ";
}
return result.slice(0, -1);
}
//확인
console.log("결과 : " + toWeirdCase("try hello world"));
📌
a['toUpperCase']()
: 출처 링크
result += word[i][parseInt(i) % 2 === 0 ? "toUpperCase" : "toLowerCase"]();
word[i]는 문자열이기 때문에["toUpperCase"]()
가 조건문에 의해서 변환 실행이 된다.
정확하게 이해한건 아니지만문자열인 경우 이렇게도 진행되는듯