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
Error List00F8 ↓ · ⇧F8 ↑
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); }}