Backdrop

프로그래머스 ▸ 코딩 기초 트레이닝

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

문제 설명

문자열 str과 정수 n이 주어집니다.
strn번 반복된 문자열을 만들어 출력하는 코드를 작성해 보세요.

제한사항

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

입출력 예

입력 #1

string 5

출력 #1

stringstringstringstringstring

풀이

이론

입력받기

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
 
let input = [];
 
rl.on('line', function (line) {
  input = line.split(' ');
}).on('close', function () {
  const str = input[0];
  const n = Number(input[1]);
});

split() 함수를 사용하여 공백을 기준으로 문자열을 나눠 배열에 저장할 수 있어요. 따라서 예를 기준으로 input에는 ['string', '5']가 저장되어 있어요. Number() 함수를 사용하여 문자열을 숫자로 바꿀 수 있어요. str에는 'string'이 저장되어 있고, n에는 5가 저장되어 있어요.

출력하기

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
 
let input = [];
 
rl.on('line', function (line) {
  input = line.split(' ');
}).on('close', function () {
  const str = input[0];
  const n = Number(input[1]);
 
  console.log(str.repeat(n));
});

반복문을 사용하지 않고도 repeat() 함수를 사용하여 문자열을 n번 반복할 수 있어요.

코드

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
 
let input = [];
 
rl.on('line', function (line) {
  input = line.split(' ');
}).on('close', function () {
  const str = input[0];
  const n = Number(input[1]);
 
  console.log(str.repeat(n));
});