
import java.util.Scanner;
public class String8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
String[] S = sentence.split(" ");
int result = 0;
for (int i = 0; i < S.length; i++) {
if(S[i].isEmpty()) continue;
result++;
}
System.out.println(result);
}
}
Scanner sc = new Scanner(System.in);
String sentence = sc.nextLine();
String[] S = sentence.split(" ");
원하는 문장 입력 후 split을 이용해 빈 공간 별로 단어를 나눴다.
int result = 0;
for (int i = 0; i < S.length; i++) {
if(S[i].isEmpty()) continue;
result++;
}
System.out.println(result);
result에 문장 단어 개수 카운팅 될 때 마다 +1 해주고, 만일 문장 맨 앞에 빈 칸이 존재한다면, split 사용해도 빈 칸은 단어로 간주되기 때문에 isEmpty() 함수 사용함으로써 해당 단어가 비어 있는지 아닌지 확인하는 작업이 필요하다.
