909. Number of words

 

Determine the number of words in the given text.

 

Input. One single line contains a text fragment in English, with a length not exceeding 250 characters. It is guaranteed that the text does not contain hyphens, dashes, or digits.

 

Output. Print the number of words in the text.

 

Sample input

Sample output

Hello world! Hello,    country!

4

 

 

SOLUTION

string

 

Algorithm analysis

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.

 

cnt = 0;

 

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

 

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.

 

cnt = 0;

 

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

 

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.

 

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

 

Print the answer.

 

print(res)