프로그래머스 코딩테스트_1

cho·2023년 11월 20일

repeat 함수

repeat() 메서드는 문자열을 주어진 횟수만큼 반복해 붙인 새로운 문자열을 반환한다.

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 () {
    str = input[0];
    n = Number(input[1]);
    console.log(str.repeat(n));
});

대소문자 바꿔서 출력하기

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

let input = [];
let arr = [];


rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
    for(let i = 0; i < str.length; i++){
        if(str[i] === str[i].toUpperCase()){
            arr.push(str[i].toLowerCase());
        } else{
            arr.push(str[i].toUpperCase());
        }
    }
    const result = arr.join("");
    console.log(result);
});
let input = []; // input은 사용자가 입력한 입력값을 담는 태그

let arr = []; // arr은 빈 그릇 태그 (결과값을 담을)

str = input[0]; // 입력된 문자열을 'str' 변수에 저장

for(let i = 0; i < str.length; i++){} // 문자열을 순회하며 각 문자의 대소문자를 변환하는 반복문

if(str[i] === str[i].toUpperCase())	
	{arr.push(str[i].toLowerCase());}
 //현재 문자가 대문자이면, 소문자로

else{arr.push(str[i].toUpperCase());}
// 소문자이면 대문자로 변환하여 배열 'arr'에 추가한다.

const result = arr.join(""); // 변환된 문자들을 빈 문자열로 연결하여 하나의 문자열로 만든다.

toUpperCase() & toLowerCase()

toUpperCase(): 이 메서드는 문자열의 모든 문자를 대문자로 변환한다.

let str = "Hello, World!";
let upperCaseStr = str.toUpperCase();

console.log(upperCaseStr); // 출력: "HELLO, WORLD!"

toLowerCase(): 이 메서드는 문자열의 모든 문자를 소문자로 변환한다.

let str = "Hello, World!";
let lowerCaseStr = str.toLowerCase();

console.log(lowerCaseStr); // 출력: "hello, world!"

join 함수

join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만든다.

array.join(separator)

'array': 문자열로 합칠 배열
'separator': 각 요소를 구분할 문자열. 생략하면 기본값으로 쉼표(',')가 사용된다.

예를 들어

let fruits = ['apple', 'banana', 'orange'];
let result = fruits.join(', '); // 각 과일을 쉼표와 공백으로 구분하여 합침

console.log(result); // 출력: "apple, banana, orange"

위 코드에서 'fruits.join(', ')'은 배열 'fruits'의 각 요소를 쉼표와 공백으로 구분하여 하나의 문자열로 만든다.

특수문자 출력하기

출력예시:
!@#$%^&*(\'"<>?:;

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


rl.on('close', function () {
    console.log(`!@#$%^&*(\\'"<>?:;`)
});

특수문자를 출력하기 위해서는 먼저 문자들을 백틱으로 감싸고, 문자열 내에서 백슬래시 \와 같이 이스케이프가 필요한 문자는 두 번 적어줘야 한다.

0개의 댓글