대문자 -> 소문자, 소문자 -> 대문자 변환

Youngho Kim·2026년 5월 8일

C++에서 대문자 ↔ 소문자 변환은 보통 tolower, toupper를 사용 (cctype 라이브러리 추가)

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

int main() {
    char c1 = 'A';
    char c2 = 'b';

    // 대문자 -> 소문자
    cout << (char)tolower(c1) << '\n'; // a

    // 소문자 -> 대문자
    cout << (char)toupper(c2) << '\n'; // B
}

문자열 전체 변환:

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

int main() {
    string s = "AbCdE";

    // 모두 소문자
    for(char &c : s) {
        c = tolower(c);
    }
    cout << s << '\n'; // abcde

    // 모두 대문자
    for(char &c : s) {
        c = toupper(c);
    }
    cout << s << '\n'; // ABCDE
}

아스키 코드로 직접 변환도 가능:

// 대문자 -> 소문자
c = c + ('a' - 'A');

// 소문자 -> 대문자
c = c - ('a' - 'A');

다만 직접 계산은 알파벳 여부 체크를 해야 해서 tolower, toupper 사용이 안전

profile
잊어버리지 않기 위해 기록하기

0개의 댓글