{ }codelper
문자열 나누기한 줄 읽기P0012

단어 세기

영어 단어들이 공백으로 나뉜 한 줄이 주어진다.
공백은 여러 개 이어질 수도 있고 줄의 앞뒤에 있을 수도 있다.
단어가 모두 몇 개인지 출력하라.

입력
길이 1 ~ 200, 단어는 1개 이상
출력
단어 수
예시 1 · stdin
  hello   big world 
stdout
3
main.py
입력(stdin)

실행하면 이 줄들이 차례로 input()·표준 입력으로 들어가요(실행 중에 묻지 않아요).

$ 준비됐어요

코드를 입력해 풀려면 PC에서 열어 주세요. 모바일에서는 문제와 풀이를 볼 수 있어요.

다른 언어로는?언어별 풀이 보기 · 8개 언어 풀이

공백이 여러 개면 나누는 방법에 따라 답이 달라요: Python split()(인자 없음)은 알아서 묶어 주지만 split(" ")는 빈 조각까지 세요.
Java는 trim() 뒤 split("\\s+"), C#은 RemoveEmptyEntries.
C·C++은 scanf("%s")·cin >>가 공백을 건너뛰어서 읽은 횟수가 곧 답이에요.

Pythonmain.py · 1 줄
print(len(input().split()))
JavaScriptmain.js · 2 줄
const line = require("fs").readFileSync(0, "utf8").split("\n")[0];console.log(line.split(" ").filter((w) => w !== "").length);
TypeScriptmain.ts · 3 줄
import { readFileSync } from "node:fs";const line: string = readFileSync(0, "utf8").split("\n")[0];console.log(line.split(" ").filter((w) => w !== "").length);
JavaMain.java · 8 줄
import java.util.Scanner; public class Main {    public static void main(String[] args) {        String line = new Scanner(System.in).nextLine().trim();        System.out.println(line.split("\\s+").length);    }}
C#Main.cs · 10 줄
using System; class Program{    static void Main()    {        string line = Console.ReadLine();        Console.WriteLine(line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);    }}
C++main.cpp · 9 줄
#include <iostream>#include <string> int main() {    std::string w;    int count = 0;    while (std::cin >> w) count++;    std::cout << count << '\n';}
Cmain.c · 9 줄
#include <stdio.h> int main(void) {    char w[201];    int count = 0;    while (scanf("%200s", w) == 1) count++;    printf("%d\n", count);    return 0;}
Craykonmain.cray · 3 줄
line = 콘솔.줄읽기();words = line.나누기("");콘솔.쓰기(words.개수);