나의 개발일지

[Algorithm][JavaScript] 프로그래머스 Level.0 - 대소문자 바꿔서 출력하기 본문

Algorithm

[Algorithm][JavaScript] 프로그래머스 Level.0 - 대소문자 바꿔서 출력하기

heew0n 2023. 11. 10. 19:09

 

✔️문제

 

영어 알파벳으로 이루어진 문자열 str이 주어집니다.

각 알파벳을 대문자는 소문자로 소문자는 대문자로 변환해서 출력하는 코드를 작성해 보세요.


 

✔️제한 사항

  • 1 ≤ str의 길이 ≤ 20
  • str은 알파벳으로 이루어진 문자열입니다.

✔️ 입출력 예

 

입력 #1

aBcDeFg

 

출력 #1

AbCdEfG

 

 


 

💡풀이

 

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];
  result = [];
  const strValue = [...str];
  strValue.map((data) => {
    if (data === data.toLowerCase()) {
      result.push(data.toUpperCase());
    } else {
      result.push(data.toLowerCase());
    }
  });
  console.log(result.join(""));
});

 

 

빈 배열을 만들고 map 함수로 모든 요소를 순회하며 조건에 맞게 출력하고

그 출력한 값을 push 메서드를 통해 배열 끝에 넣는다.

join 이라는 메서드를 새롭게 알게 되었다

 


 

Array.prototype.join

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

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"
// 빈 괄호는 배열의 형태를 제외하고 나온다

console.log(elements.join(''));
// Expected output: "FireAirWater"
// 하나의 단어로 출력된다

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"
// 단어 사이에 - 출력된다
const a = ["Wind", "Water", "Fire"];
a.join(); // 'Wind,Water,Fire'
a.join(", "); // 'Wind, Water, Fire'
a.join(" + "); // 'Wind + Water + Fire'
a.join(""); // 'WindWaterFire'