본문 바로가기
프로그래밍 연구/백준문제

[백준] 1152번 단어의 개수

by 꽈악 2022. 4. 11.
package backjun;

import java.io.IOException;
import java.util.Scanner;

public class EX1152 {

	public static void main(String[] args) throws IOException {
	    Scanner sc = new Scanner(System.in);
	    String str = sc.nextLine();
	    
		int count = 0;
		
		for(int i=0; i<str.length(); i++) {
			int t = str.charAt(i);

			if(i == 0) {
				if(t == 32 && str.length() == 1) {
					count = -1;
				} else {
					continue;
				}
				
			} else if(i == str.length()-1){
				break;
			} else {
				if(t == 32) {
					count++;
				}
			}
			
		}
		
		System.out.println(count+1);
	}

}

 

다른 답

import java.util.Scanner;
import java.util.StringTokenizer;
 
public class Main {
 
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
 
		String S = in.nextLine();
		in.close();
 
		// st 에 공백을 기준으로 나눈 토큰들을 st 에 저장한다
		StringTokenizer st = new StringTokenizer(S," ");
		
		// countTokens() 는 토큰의 개수를 반환한다
		System.out.println(st.countTokens());	
		
	}
 
}

 

피드백

- StringTokenizer 을 활용하면 편하다.

'프로그래밍 연구 > 백준문제' 카테고리의 다른 글

[백준] 2908번 상수  (0) 2022.04.12
[백준] 1157번 문자열 '단어공부'  (0) 2022.03.31
[백준] 2675번 문자열 반복  (0) 2022.03.29
[백준] 10809번 알파벳 찾기  (0) 2022.03.28