
백준 10280번-문자열 분석
문자열 N개가 주어진다. 이때, 문자열에 포함되어 있는 소문자, 대문자, 숫자, 공백의 개수를 구하는 프로그램을 작성하시오.
각 문자열은 알파벳 소문자, 대문자, 숫자, 공백으로만 이루어져 있다.
입력:
This is String
SPACE 1 SPACE
S a M p L e I n P u T
0L1A2S3T4L5I6N7E8
출력:
10 2 0 2
0 10 1 8
5 6 0 16
0 8 9 0
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = "";
while (sc.hasNextLine()) {
str = sc.nextLine();
int lowerCase = 0;
int upperCase = 0;
int num = 0;
int space = 0;
char[] charArr = str.toCharArray();
for (int i=0; i<charArr.length; i++) {
if (charArr[i] == 32) { //공백
space++;
} else if ((48 <= charArr[i]) && (charArr[i] <= 57)) { //숫자
num++;
} else if ((65 <= charArr[i]) && (charArr[i] <= 90)) { //대문자
upperCase++;
} else { //소문자
lowerCase++;
}
}
System.out.println(lowerCase + " " + upperCase + " " + num + " " + space);
}
sc.close();
}
처음에 생각했던 방법은 char 배열로 바뀌어서 해당 영소문자, 대문자, 숫자, 공백에 맞는 ASCII 코드와 동일하면 거기에 해당되는 정수형 변수의 값을 늘리는 것으로 생각을 했다.
자주 사용되는 ASCII 코드는 쓸모가 있어서 영문자는 알겠지만 숫자와 공백은 몇 번째인지 몰라서 구글링해서 풀었다.
while (sc.hasNextLine()) {
str = sc.nextLine();
int lowerCase = 0;
int upperCase = 0;
int num = 0;
int space = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
num++;
} else if (Character.isUpperCase(c)) {
upperCase++;
} else if (Character.isLowerCase(c)) {
lowerCase++;
} else {
space++;
}
}
System.out.println(lowerCase + " " + upperCase + " " + num + " " + space);
두번째 방법은 다른 사람들은 어떻게 풀었는지 구경하다보니 알게된 방법이다. Character 클래스에 있는 isDigit(), isUpperCase(), isLowerCase()를 통해서 첫번째 방법을 대체할 수 있다. 이는 ASCII 코드를 몰라도 손쉽게 풀 수 있는 방법이다. 래퍼 클래스의 메소드들을 다시 한 번 훑어봐야겠다!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = "";
StringBuilder sb = new StringBuilder();
while (sc.hasNextLine()) {
str = sc.nextLine();
int lowerCase = 0;
int upperCase = 0;
int num = 0;
int space = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
num++;
} else if (Character.isUpperCase(c)) {
upperCase++;
} else if (Character.isLowerCase(c)) {
lowerCase++;
} else {
space++;
}
}
sb.append(lowerCase).append(" ")
.append(upperCase).append(" ")
.append(num).append(" ")
.append(space).append("\n");
}
System.out.print(sb);
sc.close();
}
마지막은 String 대신 StringBuilder를 사용해서 append()를 통해서 문자열을 붙여나가는 방법이다. 다 담았다가 while문을 빠져나가면 그 때 System.out.print()를 통해 Builder에 담아둔 문자열들을 출력해준다.

위부터 세번째->두번째->첫번째 방법으로 푼 메모리와 시간이다. StringBuilder를 통해 메모리와 시간을 유의미하게 줄일 수 있었다.
래퍼 클래스의 메소드들을 다시 한 번 훑어보자. 그리고 StringBuilder를 사용하자!