본문 바로가기

Beakjoon/else

[백준] 2744번 대소문자 바꾸기 (C++)

문제

https://www.acmicpc.net/problem/2744

 

2744번: 대소문자 바꾸기

영어 소문자와 대문자로 이루어진 단어를 입력받은 뒤, 대문자는 소문자로, 소문자는 대문자로 바꾸어 출력하는 프로그램을 작성하시오.

www.acmicpc.net

코드

#include <iostream>
#include <string>

using namespace std;

int main(){
  string s;
  cin >> s;
  for(char c : s){
    if(c-'A' < 26){
      char lower = c+32;
      cout << lower;
    }else{
      char upper = c-32;
      cout << upper; 
    }
  }
  return 0;
}

정리

ASCII 코드표

ASCII 코드표

위 해결코드에서 문자 c에 +32, -32를 해준 이유는 아스키 코드에서 대문자와 소문자의 차이가 32이기 때문이다.

 

ASCII 형변환

char a = 'a';

// ASCII 수를 보여주고 싶을 때
cout << a-32 << '\n';		// 65

// ASCII 문자를 보여주고 싶을 때
char aChar = a-32;
cout << aChar << '\n';		// A

 

참조

https://stackoverflow.com/questions/4629050/convert-an-int-to-ascii-character

https://shaeod.tistory.com/228