Extract Text | ISC Computer Science 2026 Theory Sample Question

A class Extract is defined to get the text between the first and the last occurrences of a particular word from a sentence. In case the word occurs only once or does not occur at all, then the message gets displayed as “No such substring found”.

Example:
INPUT:
Sentence: It is not true that I do not like coffee
Word: not
OUTPUT:
true that I do

The details of the members of the class are given below:
Class name: Extract
Data member/instance variable:
text: to store the sentence
Methods/Member functions:
Extract(): constructor to initialize the data member with legal initial value
void readSent(): to accept a sentence
String extractText(String wrd): to extract and return the substring between the first and the last occurrence of wrd from text
void display(): to display the original sentence and the substring by invoking extractText()

Specify the class Extract giving the details of the constructor, void readSent(), String extractText(String) and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class Extract{
    String text;
    public Extract(){
        text = "";
    }
    public void readSent(){
        Scanner in = new Scanner(System.in);
        System.out.print("Sentence: ");
        text = in.nextLine();
    }
    public String extractText(String wrd){
        int first = text.indexOf(wrd);
        int last = text.lastIndexOf(wrd);
        if(first == last)
            return "";
        return text.substring(first + wrd.length(), last);
    }
    public void display(){
        Scanner in = new Scanner(System.in);
        System.out.print("The word: ");
        String wrd = in.next();
        System.out.println("Original Sentence: " + text);
        String sub = extractText(wrd);
        if(sub.equals(""))
            System.out.println("No such substring found");
        else
            System.out.println("Substring: " + sub);
    }
    public static void main(String[] args) {
        Extract obj = new Extract();
        obj.readSent();
        obj.display();
    }
}