문제

문제출처 : Baekjoon

img

풀이1

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine().trim();
        sc.close();

        if(str.isEmpty()){
            System.out.println(0);
        }else{
            String[] result = str.split(" ");
            System.out.println(result.length);
        }
    }
}

풀이2

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        String str = sc.nextLine();
        sc.close();
        
        StringTokenizer st = new StringTokenizer(str, " ");
        System.out.println(st.countTokens());

    }
}

회고

  1. split을 배우고 드디어 써먹은 날이 왔다..! 문자열이 공백으로 시작하거나 끝날수도 있다고해서 trim 메소드 을 이용해서 공백을 지워주고, string값으로 아무것도 안들어오면 1이 나오길래 0으로 입력해주었다.
  2. 풀이2는 다른 방법들에 대해서도 찾아보다가 알게 된 방법. trim도 안해도 되고 메모리도 적게 차지하고 시간도 훨씬 빠르다. 이건 나중에 정리해둬야겠다. 아주 유용한듯😏