coding test - C++/Programmers

Programmers / 대소문자 바꿔서 출력하기 / C++

sillon 2026. 2. 7. 16:58
728x90
반응형

 

*문제 출처는 프로그래머스에 있습니다.

문제 제목: 대소문자 바꿔서 출력하기

문제 사이트: https://school.programmers.co.kr/learn/courses/30/lessons/181949

 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 


나의 풀이

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string str;
    cin >> str;
    
    for(int i = 0 ; i < str.size(); i++){
        if (str[i] >= 'A' && str[i] < 'Z') // 대문자일 경우
        {
            str[i] = str[i] + ('a' - 'A');
            
        }
        else {
            str[i] = str[i] - ('a' - 'A'); // 소문자일 경우
        }
    }
    
    cout << str;
    return 0;
}

 

모범답안

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main() {
    string str;
    cin >> str;

    for (char &c : str) {
        if (isupper(c)) c = tolower(c);
        else c = toupper(c);
    }

    cout << str;
    return 0;
}

 


※ 알아야 할 것

- C++에서 ('a' - 'A')는 대문자와 소문자 사이의 ASCII 차이(32)를 의미하며, 이를 이용해 대소문자 변환을 간단한 덧셈·뺄셈으로 구현할 수 있다.

- cctype 라이브러리 활용해서도 풀 수 있다.

 

728x90
반응형