Image

Lv.0 🔗문자열 반복해서 출력하기

📝문제 요약

문제 설명

문자열 str과 정수 n이 주어집니다.

str이 n번 반복된 문자열을 만들어 출력하는 코드를 작성해 보세요.


제한사항

  • 1 ≤ str의 길이 ≤ 10
  • 1 ≤ n ≤ 5

입출력 예

입력 #1

string 5

출력 #1

stringstringstringstringstring


✏️문제 풀이

  • 입력 처리

    input = line.split(" ");
    
    • 한줄 입력 “string 5” → [string, 5]
    • 입력이 한줄이므로 바로 종료
      rl.close();
      
  • 배열에서 첫 번째와 두 번째 값을 꺼내 각각 변수 strn에 저장

    const str = input[0];
    const n = Number(input[1]);
    
  • 출력

    console.log(str.repeat(n));
    
    • repeat() 메서드를 사용하여 str을 n번 반복하여 출력
    • repeat() 메서드란?

      • repeat()은 문자열을 원하는 횟수만큼 반복해서 이어 붙인 문자열을 반환하는 JavaScript의 문자열 메서드

        str.repeat(count);
        
        // str : 반복하고 싶은 문자열
        // count : 반복할 횟수 (0 이상의 정수)
        
        • 주의사항
          • count가 음수이면 에러
          • count가 소수이면 소수점 이하는 버림 (ex. 3.9 → 3)
          • count가 너무 크면 RangeError가 발생


💯제출 코드

const readline = require("readline");
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let input = [];

rl.on("line", function (line) {
  input = line.split(" ");
  rl.close();
}).on("close", function () {
  const str = input[0];
  const n = Number(input[1]);

  console.log(str.repeat(n));
});

댓글남기기