728x90
반응형
*문제 출처는 프로그래머스에 있습니다.

문제 제목: 대소문자 바꿔서 출력하기
문제 사이트: https://school.programmers.co.kr/learn/courses/30/lessons/181949
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr

나의 풀이
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string str;
cin >> str;
for(int i = 0 ; i < str.size(); i++){
if (str[i] >= 'A' && str[i] < 'Z') // 대문자일 경우
{
str[i] = str[i] + ('a' - 'A');
}
else {
str[i] = str[i] - ('a' - 'A'); // 소문자일 경우
}
}
cout << str;
return 0;
}
모범답안
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string str;
cin >> str;
for (char &c : str) {
if (isupper(c)) c = tolower(c);
else c = toupper(c);
}
cout << str;
return 0;
}
※ 알아야 할 것
- C++에서 ('a' - 'A')는 대문자와 소문자 사이의 ASCII 차이(32)를 의미하며, 이를 이용해 대소문자 변환을 간단한 덧셈·뺄셈으로 구현할 수 있다.
- cctype 라이브러리 활용해서도 풀 수 있다.
728x90
반응형
'coding test - C++ > Programmers' 카테고리의 다른 글
| Programmers / 더 크게 합치기 / C++ (0) | 2026.02.07 |
|---|---|
| Programmers / 문자열 겹쳐쓰기 / C++ (0) | 2026.02.07 |
| Programmers / 배열의 평균값 (0단계) / C++ (2) | 2023.05.03 |
| Programmers / 짝수의 합 (0단계) / C++ (1) | 2023.05.03 |
| Programmers / 몫 구하기 (0단계) / C++ (0) | 2023.05.03 |