[C언어/C++] 문자열 대소문자 변환 (toupper, tolower) 함수 사용법 & 예제

대문자와 소문자의 아스키코드값은 32만큼의 차이가 납니다. 아스키 코드값이 다르기 때문에 컴퓨터에서는 'A'와 'a'를 같은 값으로 인식하지 않습니다. 대문자와 소문자를 같은값으로 인식시켜주기 위해서는 대문자이든 소문자이든 하나로 통일을 시켜주어야 합니다. 이러한 특징을 활용하여 대문자는 32를 더해서 소문자로 치환할 수 있고 반대로 소문자는 32를 빼주어 대문자로 치환할 수 있습니다.

#include <stdio.h>

void main()
{
    char input[1000];
    int count = 0;
    
    printf("문자열을 입력하세요 \n");
    gets_s(input);
    while (input[count]) {
        if (input[count] >= 65 && input[count] <= 90) // 대문자
            input[count] += 32; //소문자 치환
        else if (input[count] >= 97 && input[count] <= 122) // 소문자
            input[count] -= 32; //대문자 치환

        count++;
    }

    printf("%s", input);
}

대소문자 변환 예제

위와 같은 방법으로 대/소문자 변환을 하셔도 되지만 C언어/C++에서 대/소문자 변환을 위해 제공하는 대/소문자 변환 함수 tolower, toupper를 사용하셔도 됩니다. 이름에서 알 수 있듯 tolower는 소문자를 대문자로 변환하는 함수 toupper는 대문자를 소문자로 변환하는 함수입니다.

 

대소문자 변환 (toupper, tolower) 함수 사용법

#include <ctype.h> //C언어
#include <cctype> //C++

toupper(문자열) //소문자 -> 대문자 변환
tolower(문자열) //대문자 -> 소문자 변환

tolower, toupper함수를 사용하기 위해서는 해당 함수가 포함되어있는 <ctype.h> 헤더를 포함해야 합니다. C++의 경우 <cctype> 헤더를 포함하시면 됩니다. 

 

대소문자 변환 (toupper, tolower) 함수 사용 예제

#include <stdio.h>
#include <ctype.h> //C언어
#include <cctype> //C++

void main()
{
    char input[1000];
    int count = 0;
    
    printf("문자열을 입력하세요 \n");
    gets_s(input);
    while (input[count]) {
        if (isupper(input[count])){
            input[count] = tolower(input[count]);
        }
        else if (islower(input[count])){
            input[count] = toupper(input[count]);
        }
        count++;
    }

    printf("%s", input);
}

toupper tolower 예제

위와 같이 toupper, tolower함수를 사용하여 대소문자를 변환할 수 있습니다. 이 함수들을 사용할때 if문의 조건식에 대/소문자를 판별하는 함수 isupper, islower를 같이 써주는것도 좋습니다. 해당 함수의 사용법이 궁금하다면 아래의 글을 참고해주세요.

[C언어/C++] 문자열 대소문자 판별 (isupper, islower) 함수 사용법 & 예제

댓글

Designed by JB FACTORY