{ }codelper
splitting stringsreading a lineP0012

Count the words

A line of English words separated by spaces is given.
There may be several spaces in a row, and spaces at the start or end of the line.
Print the number of words.

Input
length 1 to 200, at least one word
Output
number of words
Example 1 · stdin
  hello   big world 
stdout
3
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

With repeated spaces the answer depends on how you split: Python split() (no argument) groups them, but split(" ") counts empty pieces too.
Java uses trim() then split("\\s+"), C# RemoveEmptyEntries.
In C and C++, scanf("%s") and cin >> skip whitespace, so the number of reads is the answer.

Pythonmain.py · 1 lines
print(len(input().split()))
JavaScriptmain.js · 2 lines
const line = require("fs").readFileSync(0, "utf8").split("\n")[0];console.log(line.split(" ").filter((w) => w !== "").length);
TypeScriptmain.ts · 3 lines
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 lines
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 lines
using System; class Program{    static void Main()    {        string line = Console.ReadLine();        Console.WriteLine(line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length);    }}
C++main.cpp · 9 lines
#include <iostream>#include <string> int main() {    std::string w;    int count = 0;    while (std::cin >> w) count++;    std::cout << count << '\n';}
Cmain.c · 9 lines
#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 lines
line = Console.ReadLine();words = line.Split("");Console.WriteLine(words.Count);