728x90
https://www.acmicpc.net/problem/2744
2744번: 대소문자 바꾸기
영어 소문자와 대문자로 이루어진 단어를 입력받은 뒤, 대문자는 소문자로, 소문자는 대문자로 바꾸어 출력하는 프로그램을 작성하시오.
www.acmicpc.net
문제
영어 소문자와 대문자로 이루어진 단어를 입력받은 뒤, 대문자는 소문자로, 소문자는 대문자로 바꾸어 출력하는 프로그램을 작성하시오.
입출력
입력
첫째 줄에 영어 소문자와 대문자로만 이루어진 단어가 주어진다. 단어의 길이는 최대 100이다.
출력
첫째 줄에 입력으로 주어진 단어에서 대문자는 소문자로, 소문자는 대문자로 바꾼 단어를 출력한다.
예제
예제 입력
WrongAnswer
예제 출력
wRONGaNSWER
풀이
반복문을 52개 쓰면 되긴 하는데 좀 더 좋은 방법이 있을 것 같다… 아스키 코드를 써보기로 하자
package learnString;
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
String ans = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// 대문자야?
if ('A' <= str.charAt(i) && 'Z' >= str.charAt(i)) {
// 아스키 코드값 변환
// int dist = str.charAt(i) - 'A' => 해당 대문자가 A로부터 몇칸 떨어져있는지 구하고
// int lower_ascii = 'a' + dist; => 소문자 아스키 코드로 몇번인지 구한다.
// 아래는 그걸 한번에 쓴 것
ans += (char)('a' + str.charAt(i) - 'A');
}
else ans += (char)('A' + str.charAt(i) - 'a');
}
System.out.println(ans);
}
}
String 객체를 생성하는 메모리 공간이 아깝다고 생각이 든다면 배열로charArray로 바꿔줘도 괜찮다
import java.util.Scanner;
class Main
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String str = sc.next();
char[] ans = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if ('a' <= ans[i] && ans[i] <= 'z')
ans[i] = (char)('A' + ans[i] - 'a');
else ans[i] = (char)('a' + ans[i] - 'A');
}
System.out.println(ans);
}
}
반응형
'coding test' 카테고리의 다른 글
문자열 - 백준 1157번 단어 공부 (0) | 2024.03.05 |
---|---|
문자열 - 백준 1919번 애너그램 만들기 (0) | 2024.03.04 |
2차원 배열 - 프로그래머스 교점에 별찍기 (1) | 2024.02.19 |
그래프 순회 (1) | 2024.01.31 |
그래프 (1) | 2024.01.30 |