[2003년 기말 7번] 키보드 문자열 조작 - 동적 할당 / 대소문자 변형 / 문자열 병합
목적
- 문자열을 병합한다.
- 대소문자를 변형 시킨다.
- 동적할당에 대해 이해한다.
- 키보드로 문자열을 받아 출력한다.
문제
#include <iostream>
#include <cstring>
#include <ctype.h>
using namespace std;
int main(void)
{
char sIn[255] = {0};
int iCount = 0;
char *cpA, *cpB, *cpC;
cpA = cpB = cpC = NULL;
cout << "첫번째 문자열을 입력하세요 : ";
cin.getline(sIn,255,'\n');
cpA = new char[strlen(sIn) + 1];
strcpy(cpA, sIn);
cout << "두번째 문자열을 입력하세요 : ";
cin.getline(sIn,255,'\n');
cpB = new char[strlen(sIn) + 1];
strcpy(cpB, sIn);
cpC = new char[strlen(cpA) + strlen(cpB) + 1];
strcpy(cpC, cpA);
strcat(cpC, cpB);
cout << "병합된 문자열 : " << cpC << endl;
cout << "대소문자 변환후 문자열 : ";
for(iCount = 0; iCount < strlen(cpC); iCount++)
{
if(islower(cpC[iCount])) cout << (char)(toupper(cpC[iCount]));
else cout << (char)tolower(cpC[iCount]);
}
cout << endl;
cout << "순서 뒤바뀐 문자열 : ";
for(iCount = strlen(cpC) - 1; iCount >= 0; iCount--)
{
if(islower(cpC[iCount])) cout << (char)(toupper(cpC[iCount]));
else cout << (char)tolower(cpC[iCount]);
}
cout << endl;
return 0;
}
해설
- 메모리를 동적으로 받아 넣기 위해서 문자열 포인터를 썼습니다.
- new 명령어를 통해 새로운 공간을 받아 넣습니다. 그 크기는 입력 변수에 받은 길이 + 1 [NULL 문자] 입니다.
- strcat 나 strcpy 에서는 NULL 문자를 붙여 넣거나 복사를 시도하면 연산 오류가 생깁니다.
- cout 에서는 형에서 비교적 자유롭게 출력이 가능하므로 int 형으로 리턴이 되는 tolower 나 toupper 를 정수로 나오지 않게 하기 위해 char 형으로 강제 형변환 시켰습니다.
참고
- 구글 검색 : 동적 할당
- 유사 문제