이상한 문자 만들기

이건선·2023년 2월 17일

문자열 s는 한 개 이상의 단어로 구성되어 있습니다. 각 단어는 하나 이상의 공백문자로 구분되어 있습니다. 각 단어의 짝수번째 알파벳은 대문자로, 홀수번째 알파벳은 소문자로 바꾼 문자열을 리턴하는 함수, solution을 완성하세요.

function solution(s) {
    let arr = s.split(' ')
    
    let list = []
    for (i=0;i<arr.length;i++){
        let word = arr[i].split('')
        list[i] = []
        for (j=0;j<word.length;j++){
            if(j%2==0){
                list[i].push(word[j].toUpperCase())
            }else{
                list[i].push(word[j].toLowerCase())
            }
        }
    }
    let answer;
    let str = list.join(' ');
    answer = str.replaceAll(',','')
    return answer
   
}

입력되는 단어를 split(' ')으로 짤라서 각각의 배열로 만들고 빈 배열을 하나 만든다. 그리고 for문으로 배열을 숫자만큼 첫번째 for문을 실행을 할껀데 그 안에서 두번째 for문으로 하나의 배열 안에 있는 단어의 철자 개수만큼 다시 반복을 한다 그래서 if문으로 홀수와 짝수를 판단한 다음 list[i]번째에 푸쉬를 넣어준다. list.join(" ")으로 붙이고 replaceAll(',','')을 이용해서 ,을 제거한다.

다른 풀이

function solution(s) {
  // Split the input string into an array of words
  const words = s.split(' ');

  // Transform each word in the array
  const transformedWords = words.map(word => {
    // Split the word into an array of characters
    const characters = word.split('');

    // Transform each character in the array
    const transformedCharacters = characters.map((char, index) => {
      // Use the remainder operator to check if the index is even or odd
      if (index % 2 === 0) {
        return char.toUpperCase();
      } else {
        return char.toLowerCase();
      }
    });

    // Join the transformed characters into a word and return it
    return transformedCharacters.join('');
  });

  // Join the transformed words into a string and return it
  return transformedWords.join(' ');
}
profile
멋지게 기록하자

0개의 댓글