[프로그래머스]이상한 문자 만들기

jaemin·2020년 9월 19일
0

프로그래머스

목록 보기
18/18
post-thumbnail

문제

toWeirdCase함수는 문자열을 인수로 전달받는다. 문자열 s에 각 단어의 짝수번째 인덱스 문자는 대문자로, 홀수번째 인덱스 문자는 소문자로 바꾼 문자열을 리턴하도록 함수를 완성하라.
예를 들어 s가 ‘hello world’라면 첫 번째 단어는 ‘HeLlO’, 두 번째 단어는 ‘WoRlD’로 바꿔 ‘HeLlO WoRlD’를 리턴한다.
주의) 문자열 전체의 짝/홀수 인덱스가 아니라 단어(공백을 기준)별로 짝/홀수 인덱스를 판단한다.

function toWeirdCase(s) {
}
console.log(toWeirdCase('hello world'));    // 'HeLlO WoRlD'
console.log(toWeirdCase('my name is lee')); // 'My NaMe Is LeE'

풀이 과정 설계

먼저 띄어쓰기를 기준으로 문자열을 나누고 각각의 배열을 만들고 싶었다.
이후에 각 배열을 순회하면서 짝수번째 글자는 대문자, 홀수번째 글자는 소문자로 출력하고 싶다.

풀이 과정

띄어쓰기를 기준으로 문자열을 쪼개고 각각의 배열을 만들자.

function toWeirdCase(s) {
  let strSplit = s.split(' ');
  for ( let i = 0; i < strSplit.length; i++ ) {
    console.log(strSplit[i]); // hello, world
  }
 
  return strSplit;
}

split 메서드를 이용해 띄어쓰기를 기준으로 문자열을 쪼갰다.
그런데 문제가 있었다. strSplit으로 for문을 돌면 각각의 글자, 'h','e','l' 같은 글자가 출력될줄 알았는데 단어 단위로 출력됐다.
따라서 map 함수를 이용하기로 했다.

map 함수의 설명 링크

function toWeirdCase(s) {
  let strSplit = s.split(' ');
  let strArr = strSplit.map(function(word) {
    let result = '';
    for ( let i = 0; i < word.length; i++ ){
      if ( i % 2 === 0) result += word[i].toUpperCase();
      else result += word[i].toLowerCase();
    }
    return result;
  });
  return strArr;
}

console.log(toWeirdCase('hello world'));    // [ 'HeLlO', 'WoRlD' ]
console.log(toWeirdCase('my name is lee')); // [ 'My', 'NaMe', 'Is', 'LeE' ]

현재 strSplit는 배열 [ 'hello', 'world' ]이다. 각 글자에 접근하기 위해 map 함수를 이용했다.
map 함수의 매개변수 word는 strSplit의 요소인 'hello'와 'world'이다. word의 길이만큼 for문을 돌면서 인덱스가 짝수면 대문자로 인덱스가 홀수면 소문자로 변환한후 빈 문자열 result에 저장한다.
이후 strArr을 리턴하면 결과는 배열인 [ 'HeLlO', 'WoRlD' ]가 출력된다.
우리가 원했던 결과는 배열이 아니라 문자열이므로 배열이 아닌 문자열로 변환해 주는 과정이 필요하다.

function toWeirdCase(s) {
  let strSplit = s.split(' ');
  let strArr = strSplit.map(function(word) {
    let result = '';
    for ( let i = 0; i < word.length; i++ ){
      if ( i % 2 === 0) result += word[i].toUpperCase();
      else result += word[i].toLowerCase();
    }
    return result;
  });
  return strArr.join(' ');
}

console.log(toWeirdCase('hello world'));    // 'HeLlO WoRlD'
console.log(toWeirdCase('my name is lee')); // 'My NaMe Is LeE'

당연한 말이지만 join() 함수는 배열의 원소를 하나의 값으로 바꿔주므로 문자열에는 사용할 수 없다.
바보같이 문자열인 result에 join함수를 적용하고 왜 안되는지 애를 먹었다.

다른 사람의 풀이

function toWeirdCase(s) { 
  let result = ''; 
  let count = 0; 
  for (let i = 0; i < s.length; i++) {
    result += count % 2 === 0 
      		? s[i].toUpperCase() : s[i].toLowerCase();
    count = s[i] === ' ' ? 0 : ++count; 
  } 
  return result;
} 
console.log(toWeirdCase('hello world')); // 'HeLlO WoRlD' 
console.log(toWeirdCase('my name is lee')); // 'My NaMe Is LeE'

동기가 작성한 코드이다. 삼항 조건 연산자를 잘 활용하여 깔끔하게 구현하였다.
잘 생각하면 어려운 메서드를 사용하지 않아도 가독성 좋은 코드를 만들 수 있다는걸 깨달았다.

function toWeirdCase(s) {
  let sentence = s.split(' ');
  let word = '';
  for(let i = 0; i < sentence.length; i++){
    for(let j = 0; j < sentence[i].length; j++){
      if(j % 2 === 0){
        word += sentence[i][j].toUpperCase();
      } else{
        word += sentence[i][j];
      }
    }
    word += ' ';
  }
  return word;
}
console.log(toWeirdCase('hello world'));    // 'HeLlO WoRlD'
console.log(toWeirdCase('my name is lee')); // 'My NaMe Is LeE'

다른 동기의 풀이에서는 이중 for문으로 접근했다.

profile
프론트엔드 개발자가 되기 위해 공부 중입니다.

1개의 댓글

comment-user-thumbnail
2020년 9월 20일

다른 사람의 풀이도 비교하면서 공부하는 모습이 너무 멋집니다👍👍👍

답글 달기