[C++] tolower, toupper 대소문자 변환

안녕하세요 오늘은, C++의 대소문자 변환하는 함수 tolower, toupper 함수를 알아보겠습니다.
tolower, toupper함수는 인자로 1개의 아스키 코드 값을 전달 하면 해당 문자의 대소문자를 변환해 줍니다.

대문자 -> 소문자로 변환하는 tolower의 함수 원형은 아래와 같습니다.

int tolower(
   int c
);
int _tolower(
   int c
);
int towlower(
   wint_t c
);
int _tolower_l(
   int c,
   _locale_t locale
);
int _towlower_l(
   wint_t c,
   _locale_t locale
);

msdn에서는 tolower을 수행하기 위해서 __isascii 함수와 isupper 함수를 수행해야 개발자가 예상되는 결과를 제공한다고 합니다.

msdn을 참고하여 함수를 만들면 아래와 같습니다.

#include <iostream>

using namespace std;

void main()
{
	// 대문자 -> 소문자
	char acToLower[260] ={"~hELlo WorLd!"};
	int iLen = strlen(acToLower);

	for ( int iLoop = 0 ; iLoop < iLen ; iLoop++ )
	{
		int iIsAscii = __isascii(acToLower[iLoop]); // ASCII인지 판단(성공 시 0이 아닌 값)
		int iIsUpper = isupper(acToLower[iLoop]); // 대문자인지 판단(성공 시 0이 아닌값)
		
		if ( (0 != iIsAscii) && (0 != iIsUpper) )
		{
			char c = acToLower[iLoop];
			acToLower[iLoop] = tolower(c); // 성공 시 소문자 ASCII 값 반환
		}
	}
}

acStr에서 ASCII이고 대문자인 “~hELlo WorLd!”만 변환 됩니다.(굵은 글자)
소문자 -> 대문자로 변환하는 toupper의 함수 원형은 아래와 같습니다.

int toupper(
   int c
);
int _toupper(
   int c
);
int towupper(
   wint_t c
);
int _toupper_l(
   int c ,
   _locale_t locale
);
int _towupper_l(
   wint_t c ,
   _locale_t locale
);

이 함수 또한 __isascii 함수와 islower 함수를 같이 수행해야 개발자가 예상되는 결과를 제공한다고 합니다.

toupper 예제 함수는 아래와 같습니다.

using namespace std;

void main()
{
	// 소문자 -> 대문자
	char acToUpper[260] ={"~hELlo WorLd!"};
	iLen = strlen(acToUpper);

	for( int iLoop = 0; iLoop < iLen; iLoop++ )
	{
		int iIsAscii = __isascii(acToUpper[iLoop]); // ASCII인지 판단(성공 시 0이 아닌 값)
		int iIsLower = islower(acToUpper[iLoop]); // 소문자인지 판단(성공 시 0이 아닌값)

		if( ( 0 != iIsAscii ) && ( 0 != iIsLower ) )
		{
			char c = acToUpper[iLoop];
			acToUpper[iLoop] = toupper(c); // 성공 시 대문자 ASCII 값 반환
		}
	}
}

acStr에서 ASCII이고 소문자인 “~hELlo WorLd!”만 변환 됩니다.(굵은 글자)

전체 코드는 아래와 같습니다.

#include <iostream>

using namespace std;

void main()
{
	// 대문자 -> 소문자
	char acToLower[260] ={"~hELlo WorLd!"};
	int iLen = strlen(acToLower);

	for ( int iLoop = 0 ; iLoop < iLen ; iLoop++ )
	{
		int iIsAscii = __isascii(acToLower[iLoop]); // ASCII인지 판단(성공 시 0이 아닌 값)
		int iIsUpper = isupper(acToLower[iLoop]); // 대문자인지 판단(성공 시 0이 아닌값)
		
		if ( (0 != iIsAscii) && (0 != iIsUpper) )
		{
			char c = acToLower[iLoop];
			acToLower[iLoop] = tolower(c); // 성공 시 소문자 ASCII 값 반환
		}
	}

	// 소문자 -> 대문자
	char acToUpper[260] ={"~hELlo WorLd!"};
	iLen = strlen(acToUpper);

	for( int iLoop = 0; iLoop < iLen; iLoop++ )
	{
		int iIsAscii = __isascii(acToUpper[iLoop]); // ASCII인지 판단(성공 시 0이 아닌 값)
		int iIsLower = islower(acToUpper[iLoop]); // 소문자인지 판단(성공 시 0이 아닌값)

		if( ( 0 != iIsAscii ) && ( 0 != iIsLower ) )
		{
			char c = acToUpper[iLoop];
			acToUpper[iLoop] = toupper(c); // 성공 시 대문자 ASCII 값 반환
		}
	}
}