‹ Back to the paper
Question 8
10 marks
Computer ScienceISC 2026 Improvement Computer Science Paper 1ProgramObjects
Write the program described below.
A class Extract is defined to get the text between the first and the last occurrences of a…
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:
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.
| 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( ) |
Answer
Answer
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.