Image

Lv.0 🔗대소문자 바꿔서 출력하기

📝문제 요약

문제 설명

영어 알파벳으로 이루어진 문자열 str이 주어집니다. 각 알파벳을 대문자는 소문자로 소문자는 대문자로 변환해서 출력하는 코드를 작성해 보세요.


제한사항

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

입출력 예

입력 #1

aBcDeFg

출력 #1

AbCdEfG


✏️문제 풀이

  1. 입력 처리

    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 () {
      // 나중에 로직 실행
    });
    
    • readline 모듈을 사용해 입력을 받음
    • 한 줄의 문자열을 입력받아 input[0]에 저장
    • 입력이 한 줄이므로 input = [line];로 처리하고 바로 close() 호출
  2. 문자열 처리 로직

    str = input[0]; // 입력된 문자열
    
    let value = ""; // 결과 문자열
    
    for (let i = 0; i < str.length; i++) {
      if (str[i] == str[i].toUpperCase()) {
        value += str[i].toLowerCase(); // 대문자 → 소문자
      } else {
        value += str[i].toUpperCase(); // 소문자 → 대문자
      }
    }
    
    • 문자열의 각 문자를 확인하면서
      • 대문자면 소문자로 : toLowerCase()
      • 소문자면 대문자로 변환 : toUpperCase()
    • value에 변환된 문자를 하나씩 추가
  3. 출력

    console.log(value); // 변환된 문자열 출력
    
    • 최종 결과인 value를 콘솔에 출력


💯제출 코드

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 value = "";

  for (let i = 0; i < str.length; i++) {
    if (str[i] == str[i].toUpperCase()) {
      value += str[i].toLowerCase();
    } else {
      value += str[i].toUpperCase();
    }
  }
  console.log(value);
});

댓글남기기