Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Word Extraction and Count

Updated 21 Oct 2026

This program reads a sentence, picks out each word one by one using only charAt(), substring() and length(), prints every word on its own line with its length, and prints the number of words. It does not use StringTokenizer or split(). Everything is written in the main method.

Definition

A word here is a run of characters between spaces. The sentence must end with ., ? or !; if it does not, the program prints INVALID INPUT. The decisions the program makes are:

  • The terminating character (., ? or !) is not part of the last word. In Hello. the word is Hello, of length 5.
  • Several spaces in a row, and spaces at the start of the sentence, are skipped. They never produce an empty word.
  • A space before the terminating character (as in Is it raining ?) is fine; ? alone is not counted as a word.
  • Spaces at the end of the line are ignored too (the program trims the line), so Hello. is valid.
  • A sentence with only the terminating character, such as ., has no word at all, so it is INVALID INPUT.

Algorithm

  1. Read the sentence into s and remove the spaces at its two ends with trim().
  2. The sentence is valid only if it has at least 2 characters and its last character is ., ? or !. If not, print INVALID INPUT and stop.
  3. Set start = -1 (no word is open) and count = 0. For every index i of the sentence:
    • if the character is a space, or i is the last index (the terminator), it is a separator: if a word is open (start != -1), the word is s.substring(start, i); add 1 to count, print the word with its length and set start = -1;
    • otherwise, if no word is open, this is the first letter of a new word, so set start = i.
  4. After the loop print the number of words.

Program

The single for loop in main opens a word at its first letter and closes it at the next space or at the terminator.

import java.util.Scanner;

/* Program Words reads a sentence, extracts its words without using StringTokenizer
   or split(), prints each word with its length and prints the word count. */
public class Words
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String s = sc.nextLine().trim();         // trim() removes the spaces at the two ends
        int len = s.length();                    // length of the sentence
        boolean valid = false;                   // true if there is a word and a terminator . ? or !
        if (len >= 2)                            // empty, or only a terminator, is invalid
        {
            char last = s.charAt(len - 1);       // terminating character
            valid = last == '.' || last == '?' || last == '!';
        }
        if (!valid)
        {
            System.out.println("INVALID INPUT");
            return;
        }
        int start = -1;                          // index where the current word begins, -1 if none
        int count = 0;                           // number of words found
        for (int i = 0; i < len; i++)
        {
            char ch = s.charAt(i);               // character being examined
            if (ch == ' ' || i == len - 1)       // separator: a word may have just ended
            {
                if (start != -1)
                {
                    String w = s.substring(start, i);    // the word found
                    count++;
                    System.out.println(w + " (" + w.length() + ")");
                    start = -1;
                }
            }
            else if (start == -1)                // first letter of a new word
                start = i;
        }
        System.out.println("Number of words = " + count);
    }
}

Variable description table

VariableData TypePurpose
argsString[]Command line arguments of main; not used
scScannerReads the input typed by the user
sStringThe sentence typed by the user, after trim()
lenintLength of the sentence
validbooleanTrue if the sentence has a word and ends with ., ? or !
lastcharThe last character of the sentence, the terminator
startintIndex where the current word begins, -1 if no word is open
countintNumber of words found
iintLoop counter over the characters
chcharThe character being examined
wStringThe word found, printed with its length

Sample input and output

Sample 1

Enter a sentence:   The   sun rises  in the east!
The (3)
sun (3)
rises (5)
in (2)
the (3)
east (4)
Number of words = 6

Sample 2

Enter a sentence: Hello.
Hello (5)
Number of words = 1

Sample 3

Enter a sentence: Is it raining ?
Is (2)
it (2)
raining (7)
Number of words = 3

Sample 4

Enter a sentence: Good morning
INVALID INPUT

Sample 5

Enter a sentence: .
INVALID INPUT

Sample 6

Enter a sentence: Good evening.   
Good (4)
evening (7)
Number of words = 2

One value per line

Dry run

Take the third sample, Is it raining ?. The characters are at indices: I0 s1 space2 i3 t4 space5 r6 a7 i8 n9 i10 n11 g12 space13 ?14, so len = 15.

ichstart beforeActionwcount after
0I-1start = 00
1s0none0
2space0word endsIs1
3i-1start = 31
4t3none1
5space3word endsit2
6r-1start = 62
7 to 12a i n i n g6none2
13space6word endsraining3
14?-1last index: separator, but no word open3

The program prints Is (2), it (2), raining (7) and Number of words = 3, the same as the real run above.

Exam tip: Use substring(start, i): its end index is excluded, so the space or terminating character is left out of the word.

Variations

  1. Longest word "Accept a sentence and display the longest word and its length."
  2. Reverse each word "Accept a sentence and display it with every word reversed, keeping the order of the words."
  3. Words starting with a vowel "Accept a sentence and count the words that begin with a vowel."
  4. Reverse word order "Accept a sentence and display its words in reverse order."