Posts [Java] 백준 #1152: 단어의 개수 (Java)
Post
Cancel

[Java] 백준 #1152: 단어의 개수 (Java)

문제

영어 대소문자와 띄어쓰기만으로 이루어진 문자열이 주어진다. 이 문자열에는 몇 개의 단어가 있을까? 이를 구하는 프로그램을 작성하시오. 단, 한 단어가 여러 번 등장하면 등장한 횟수만큼 모두 세어야 한다.

풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.Scanner;

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

    for (int i = 1; i < str.length() - 1; i++) {
      if (str.charAt(i) == 32) {
        count++;
      }
    }

    if (str.length() == 0 || str.equals(" ")) {
      System.out.println(0);
    } else {
      System.out.println(count);
    }
  }
}
This post is licensed under CC BY 4.0 by the author.

[JS] 생활코딩 #22: 전역객체

[Java] 백준 #2908: 상수

Loading comments from Disqus ...