loading
본문 바로가기
Language/C, C++

[C++] 영어 알파벳 대문자 소문자 변환 총정리

by 개발자 김모씨 2020. 11. 5.
반응형

<C++ 영어 알파벳 대소문자 변환 총정리>

 

안녕하세요.
개발자 김모씨입니다.

다들 영어 대소문자간 변환할 때 구글링 해본 경험 있으시죠?

오늘은, 영어 대소문자 변환 방법을 총정리 해보겠습니다.

 

1. 직접 연산

코딩의 묘미는 역시 밑바닥부터 직접 해보는 거죠?
모든 함수는 쓰기 전에, 원리를 알아야 하는 법입니다.
원리를 이해하고 나서, 이미 구현된 함수를 쓸 때 더 효율적으로 쓸 수 있죠.


로우레벨로 직접 짜봅시다!!! (근엄)

#include <iostream>
#include <string>
#include <ctype.h>

using namespace std;

int mytolower(int c)
{
    if ((c >= 'A') && (c <= 'Z'))
    {
        c = c - 'A' + 'a';
    }
    return c;
}
int mytoupper(int c)
{
    if ((c >= 'a') && (c <= 'z'))
    {
        c = c - 'a' + 'A';
    }
    return c;
}

int main() {
    string str = "Hello World";
    cout << "Origin : " << str << endl;
    
    for(int i = 0; i < str.size(); i++) {
    	str[i] = mytolower(str[i];
    }
    cout << "ToLower : " << str << endl;
    
    for(int i = 0; i < str.size(); i++) {
    	str[i] = mytoupper(str[i];
    }
    cout << "ToUpper : " << str << endl;
    
    return 0;
}
// 실행 결과

Origin : Hello World
ToLower : hello world
ToUpper : HELLO WORLD

이렇게, 아스키코드 값을 이용하여 함수를 직접 구현할 수 있습니다.
이 코드는 C언어에서도 쓸 수 있겠죠?

 

2. toupper(), tolower() 함수

네 맞아요! 위에서 구현한 toupper, tolower 함수는 이미 구현되어 있습니다.
가져다 쓰면 훨씬 편하죠?

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Hello World";
    cout << "Origin : " << str << endl;
    
    for(int i = 0; i < str.size(); i++) {
    	str[i] = tolower(str[i];
    }
    cout << "ToLower : " << str << endl;
    
    for(int i = 0; i < str.size(); i++) {
    	str[i] = toupper(str[i];
    }
    cout << "ToUpper : " << str << endl;
    
    return 0;
}
// 실행 결과

Origin : Hello World
ToLower : hello world
ToUpper : HELLO WORLD

같은 결과가 나오게 되죠.

여기서 사용한 toupper(), tolower() 함수는 하기 링크에서 확인하세요.
www.cplusplus.com/reference/cctype/toupper/

 

toupper - C++ Reference

function toupper Convert lowercase letter to uppercase Converts c to its uppercase equivalent if c is a lowercase letter and has an uppercase equivalent. If no such conversion is possible, the value returned is c unchanged. Notice that what is con

www.cplusplus.com

www.cplusplus.com/reference/cctype/tolower/

 

tolower - C++ Reference

function tolower Convert uppercase letter to lowercase Converts c to its lowercase equivalent if c is an uppercase letter and has a lowercase equivalent. If no such conversion is possible, the value returned is c unchanged. Notice that what is con

www.cplusplus.com

 

 

3. _strupr_s(), _strlwr_s() 함수

C++ 에는 _strupr_s(), _strlwr_s() 함수가 있습니다.
(기존 strupr(), strlwr()에서 오버플로우를 방지하기 위해 _s 가 붙은 포맷으로 업그레이드 됐죠.)

strupr은 'string upper'의 약자입니다.

errno_t _strupr_s(
   char *str,
   size_t numberOfElements
);

이런 포맷을 가집니다. 뒤에 size_t 값을 넣어줘야 하죠.

strlwr은 'string lower'의 약자입니다.

errno_t _strlwr_s(
   char *str,
   size_t numberOfElements
);

마찬가지로 이런 포맷을 가집니다.

이 함수들을 사용해서, 알파벳 대소문자 변환을 구현해보면

#include <iostream>
#include <cstring>
#include <string.h>

using namespace std;

int main()
{
    string str = "Hello World";
    cout << "Origin : " << str << endl;
    
    CString cStr = str.c_str();
    
    _strlwr_s(cStr, sizeof(cStr));
    str = CT2CA(cStr);
    cout << "ToLower : " << str << endl;
    
    _strupr_s(cStr, sizeof(cStr));
    str = CT2CA(cStr);
    cout << "ToUpper : " << str << endl;
    
    return 0;
}
// 실행 결과

Origin : Hello World
ToLower : hello world
ToUpper : HELLO WORLD

이렇게 됩니다.

CString으로 변환을 해야 하고, 중간중간 귀찮은 부분들이 있지만,
이런 것도 있다~ 정도로 알아둡시다!

아, 그리고
_strupr_s(), _strlwr_s() 함수는 원본 데이터를 변환하기 때문에,

_strlwr_s("Hello World", 11);

이런 식으로, 문자열 상수를 바로 사용하면 오류가 발생합니다.
문자열 상수의 값을 변경할 수 없기 때문이죠.
알아둡시다!

 

 

 

자 오늘은 이렇게 C++의 영어 알파벳 대소문자 변환에 관해 알아보았습니다.

잘 익혀두었다가
필요한 순간에 바로바로 기억에서 꺼내서 사용합시다!

 

그럼 오늘은 여기까지!

좋아요와 구독하기는 개발자 김모씨에게 큰 힘이 됩니당당당

 

감사합니당당당

반응형

'Language > C, C++' 카테고리의 다른 글

[C++] STL List 사용법  (0) 2022.05.03
[C++] STL Vector 사용법  (2) 2020.11.16
[C++] transform 함수  (0) 2020.11.03

댓글