Number of words#909

Number of words (Editorial)

Read the words until the end of the file and count them.

Algorithm implementation

Declare the array.

char s[300];

Count the number of the words in the variable .

cnt = 0;

Read the input data until the end of the file. After reading the word , increase the variable by .

while (scanf("%s",s) == 1)
  cnt++;

Print the answer.

printf("%d\n",cnt);

Algorithm implementation — string

Count the number of the words in the variable .

cnt = 0;

Read the input data until the end of the file. After reading the word , increase the variable by .

while (cin >> s) cnt++;

Print the answer.

cout << cnt << endl;

Java implementation

import java.util.*;

public class Main 
{
  public static void main(String[] args) 
  {
    Scanner con = new Scanner(System.in);
    int cnt = 0;
    while(con.hasNext())
    {
      con.next(); cnt++;
    }
    System.out.println(cnt);
    con.close();
  }
}

Python implementation

Read the input string. Convert it into a list of words. Compute the length of the list .

res = len(input().split())

Print the answer.

print(res)