백준 > 문자열 분석

jinvicky·2023년 12월 8일
0

ALG

목록 보기
13/62
post-thumbnail

문자열 분석

문자열 N개가 주어졌을 때, 문자열에 포함되어 있는 소문자, 대문자, 숫자, 공백의 개수를 구하기

package src.baekjoon;

import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int[] result = new int[4];
        String str = "";


        while ((str = br.readLine()) != null) {
            for (int i = 0; i < str.length(); i++) {
                Character ch = str.charAt(i);

                if (ch == ' ') {
                    result[3]++;
                } else if (Character.isDigit(ch)) {
                    result[2]++;
                } else if (ch - 97 >= 0) {
                    result[0]++;
                } else {
                    result[1]++;
                }
            }

            String tmp = "";
            for (int i = 0; i < result.length; i++) {
                tmp += result[i] + " ";
            }
            bw.append(tmp.trim() + "\n");

            //배열 초기화
            result = new int[]{0, 0, 0, 0};
        }

        bw.flush();
        bw.close();
    }
}

결과

정답

풀이

알파벳 단어 문제에서 사용했던 빼기 방법을 사용해 보았다. (charAt(i) - 97)

보통 백준은 N으로 먼저 입력할 문장 등의 수를 입력받는데 이번에는 제한이 없었다.

... 중략 ... 
String str = "";
while ((str = br.readLine()) != null) {
            for (int i = 0; i < str.length(); i++) {

위 부분이 정답이지만 인텔리제이에서 돌릴 때는 바로 정답을 내놓지는 않는다.
참고로 아래는 오답이다. NullPointerException이 뜬다.

... 중략 ... 
String str = "";
while(!(str = br.readLine()).equals("")) {
            for (int i = 0; i < str.length(); i++) {

소요 시간

1시간 내

profile
일단 쓰고 본다

0개의 댓글