2차 공부/알고리즘

대소문자 바꿔서 출력하기

공대탈출 2024. 5. 6. 22:10

내가 작성한 코드

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

let input = [];

rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
    let out = ''
    for (let i = 0; i < str.length; i++) {
        if (str[i] == str[i].toUpperCase()) {
            out += str[i].toLowerCase()
        } else if
            (str[i] == str[i].toLowerCase()) {
            out += str[i].toUpperCase()
        }
    }
    console.log(out)
});

반복문과 조건문을 사용하여 문자열의 인덱스마다 대소문자를 구분하고 상황에 맞게 바꾸도록 만들었다.

 

다른사람이 작성한 코드

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

let input = [];

rl.on('line', function (line) {
    input = [line];
}).on('close',function(){
    str = input[0];
    const regex = /[A-Z]/
    console.log([...str].map((v)=> 
    	regex.test(v) ? v.toLowerCase() : v.toUpperCase()).join('')
    )
});

map메소드에 전개연산자를 사용해 문자열을 분리해서 배열에 넣고, 각 요소마다 정규표현식 테스트를 거친 후 각각 대소문자화 하여 join()메소드로 문자열화 시켰다.

 

정규표현식은 예전부터 이해하기 어려웠는데 조금 더 노력해야할 것 같다.

 

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase

 

String.prototype.toUpperCase() - JavaScript | MDN

toUpperCase() 메서드는 문자열을 대문자로 변환해 반환합니다.

developer.mozilla.org

https://hitomis.tistory.com/68

 

[javascript] 자주 사용하는 정규 표현식 (Regular Expression) 정리

정규표현식 패턴 /패턴/ 대표적인 패턴 의미 패턴 의미 x 문자 x xyz 문자 xyz [xyz] x,y,z 중 하나의 문자 [a-z] a~z중 하나의 문자 [^xyz] x,y,z 가 아닌 하나의 문자 [^a-z] a~z가 아닌 하나의 문자 abc|xyz 문자

hitomis.tistory.com

 

'2차 공부 > 알고리즘' 카테고리의 다른 글

문자열 붙여서 출력하기  (0) 2024.05.07
덧셈식 출력하기  (0) 2024.05.06
특수문자 출력  (0) 2024.05.06
문자열 반복해서 출력하기  (0) 2024.05.06
홀짝에 따라 다른 값 반환하기  (0) 2024.05.06