본문 바로가기
알고리즘 풀이

[백준] 1152번: 단어의 개수 - java 풀이

by 코디드 2023. 6. 16.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws IOException{
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		StringTokenizer st = new StringTokenizer(br.readLine());
		
//		int cnt=0;
//		while(st.hasMoreElements()) {
//			String word = st.nextToken();
//			
//			cnt++;
//		}
//		
//		System.out.println(cnt);
		
		System.out.println(st.countTokens());
		
	}
}

 

split() 으로 풀면 제일 앞에 공백이 있을때 숫자가 하나 더 추가되어 나온다. trim()으로 공백을 제거해도 빈 문자열로 인식된다고 한다. 

 

원래 풀던대로 StringTokenizer를 이용해서 따로 개수를 세주거나 아예 StringTokenizer.countTokens()를 해서 개수를 구해주면 된다.