본문 바로가기

Programing/C/C++

C++ 대문자 <-> 소문자 변환 종합 정리

C++ 대문자 <-> 소문자 변환 종합 정리(char, cstring, string)


char 변환


 #include <cctpye>

 char c='a';


 toupper(c);

 tolower(c);


원본 c는 변경한 값을 반환한다. 안되는 경우(이미 적용되었거나 특수문자 등)는 그대로 c를 반환하니 주의없이 사용 가능하다.


다만 함수 원형은


in toupper(int), int tolower(int) 이기 때문에

cout<<toupper('a');

같은 경우에는 65('A'에 해당)이 반환되므로 형변환이 필요하다.








cstring 변환


#include <cstring>

 

char s[] = "abcABC,.!";

 

//strupr(s);

//strlwr(s);

 

_strupr_s(s);    // s를 대문자로 변경. 반환 값은 오류처리 코드.

_strlwr_s(s);    // s를 소문자로 변경. 반환 값은 오류처리 코드.

구버전 함수보다는 안정성이 높아진 새 함수를 사용하는 것이 좋다.


원본을 바꿔버리기 때문에 원본이 필요한 경우 복사본을 만들고 사용하는 편이 좋다.

Multi-Byte, Unicode 모두 사용 가능하다.







string 변환


#include <cctype>

#include <string>

#include <algorithm>

 

std::string a = "abcABC.,!";

 

std::transform(a.begin(), a.end(), a.begin(), toupper);    // a를 대문자로 변경

std::transform(a.begin(), a.end(), a.begin(), tolower);    // a를 소문자로 변경

STL의 transform algorithm을 이용한 방법이다.

transform은 특정 구간의 값을 함수를 이용해 변경하면서 다른 구간으로 옮긴다.

활용에 따라 원본을 유지, 대치 모두 할 수 있으며 자세한 방법은 STL을 공부하길 바란다.


출처 : http://neodreamer.tistory.com/267

출처 : http://msdn.microsoft.com/en-us/library/sae941fh(v=vs.80).aspx

출처 : http://www.cplusplus.com/reference/clibrary/cctype/toupper/

       http://www.cplusplus.com/reference/clibrary/cctype/tolower/

       http://maytrees.tistory.com/118