Java | 단어의 개수[백준 1152]

나경호·2022년 4월 9일
0

알고리즘 Algorithm

목록 보기
59/106

단어의 개수

출처 | 단어의 개수[백준 1152]

문제

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

입력

첫 줄에 영어 대소문자와 공백으로 이루어진 문자열이 주어진다. 이 문자열의 길이는 1,000,000을 넘지 않는다. 단어는 공백 한 개로 구분되며, 공백이 연속해서 나오는 경우는 없다. 또한 문자열은 공백으로 시작하거나 끝날 수 있다.

출력

첫째 줄에 단어의 개수를 출력한다.


풀이 1

// ver.1

import java.io.*;

public class Main{
        
    
	public static void main(String[] args) throws IOException{
        
		BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));

        String trimmed = scan.readLine().trim();
	    String [] text;
        if (trimmed.length() != 0) {
            text = trimmed.split(" ");
        } 
        else {
            text = new String[0];
        }
        
        if (text.length == 1 && text[0].equals("")) {            
            System.out.print(text.length - 1);
        }
        else{
            System.out.print(text.length);
        }
    }
}

풀이 2

// ver.2

import java.io.*;
import java.util.*;

public class Main{
        
    
	public static void main(String[] args) throws IOException{
        
		BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
        String text = scan.readLine().trim();
        StringTokenizer st = new StringTokenizer(text);

        int count = 0;
        System.out.print(st.countTokens());

    }
}

풀이 3

// ver.3

import java.io.*;
import java.util.*;

public class Main{
        
    
	public static void main(String[] args) throws IOException{
        
		BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));    
        String text = scan.readLine();
        int count = 1;
        for (int i = 1; i < text.length(); i++) {
            if (text.charAt(i) != ' ') {
                continue;
            }
            else {
                count += 1;
            }            
        }
        if (text.equals("")) {
                count = 0;
        }
        System.out.print(count);
    }
}

출처

알고리즘 분류

profile
기억창고👩‍🌾

0개의 댓글