1152. 단어의 개수

개붕이·2023년 12월 3일

Baekjoon

목록 보기
7/12

문제

풀이

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

        String s = br.readLine(); 
        StringTokenizer st = new StringTokenizer(s);
        int count = 0;
        while (st.hasMoreElements()){
            s = st.toString();
            if(s.charAt(0) == ' '){
                count++;
            }else if(s.charAt(s.length()-1) == ' ' && st.countTokens() == 0){
                count++;
            }
            st.nextToken();
            count ++;
        }
        // 1. StringTokenizer에 요소 값이 있으면 << 을 조건으로 for loop
        // 2. String s의 첫 번째 값이 공백이면 count++, 아닌 경우의 if문은 끝 문자가 공백 and 남은 토큰이 0일 때 count++
        // 3. 조건문 이후엔 정상적인 단어 count 로직
        // loop를 돌 때 st.toString으로 문자열을 재할당하여 if문 검증
        bw.write(String.valueOf(count));
        bw.flush();
        bw.close();
        br.close();
    }
}
profile
based on the records

0개의 댓글