PRASHNIKAप्रश्निका
Back to the paper

A class Extract is defined to get the text between the first and the last occurrences of a…

Computer Science202610 marksProgram
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 initialise 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.

Answer

Answer

AI
import java.util.Scanner;

class Extract
{
    String text;

    Extract()
    {
        text = "";
    }

    void readSent()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        text = sc.nextLine();
    }

    String extractText(String wrd)
    {
        int first = text.indexOf(wrd);
        int last = text.lastIndexOf(wrd);
        if (first == -1 || first == last)
            return "No such substring found";
        int start = first + wrd.length();
        return text.substring(start, last).trim();
    }

    void display()
    {
        System.out.println("Original sentence: " + text);
        System.out.println("Substring: " + extractText("not"));
    }

    public static void main(String[] args)
    {
        Extract obj = new Extract();
        obj.readSent();
        obj.display();
    }
}
Explanation: extractText(wrd) finds the first and last occurrence of wrd in text using indexOf() and lastIndexOf(). If wrd occurs only once or not at all (first==-1 or first==last), it returns the 'No such substring found' message; otherwise it returns the trimmed substring strictly between the end of the first occurrence and the start of the last occurrence. Tested (run for real) with the sentence 'It is not true that I do not like coffee' and word 'not': output was 'Substring: true that I do', matching the example in the question.
Objects

From ISC 2026 Improvement Computer Science Paper 1, question 8.