Write the program described 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( ) |
Show 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.