[Programmers] 문자 반복 출력하기

그래도 해야지·2023년 4월 4일
0

Programmers

목록 보기
4/40
post-thumbnail

문제 설명
문자열 my_string과 정수 n이 매개변수로 주어질 때, my_string에 들어있는 각 문자를 n만큼 반복한 문자열을 return 하도록 solution 함수를 완성해보세요.

🤔 해설

  1. 처음에 문자열 반복이라서 repeat을 이용해서 풀었지만 repeat을 이용하니 문자열 전체가 반복이 되는 것이다.
    test)
function solution(my_string, n) {

my_string.repeat(n)	// hellohellohello 출력
}

하지만 문제에서 요구하는 것은 문자열 전체를 n만큼 반복이 아니라 문자열 하나하나를 n만큼 반복해야하는 것!!
hellohellohello (x)
hhheeellllllooo (o)

  1. 먼저 split을 써서 문자열을 배열로 만들어줌
const arr = my_string.split('') // ['h', 'e', 'l', 'l', 'o']
  1. 배열 요소 하나하나를 n번만큼 반복해야함
   const mapArr = arr.map((word)=>{return word.repeat(n)})
  1. 요소 하나하나 반복한 것을 문자열로 만들어줌
mapArr.join('')

✅ 답

function solution(my_string, n) {
   const arr = my_string.split('')
   const mapArr = arr.map((word)=>{return word.repeat(n)})
   return mapArr.join('')
}

0개의 댓글