sriram s sriram s - 19 days ago 5
Java Question

Find the last index of a word(string) from a String(paragraph) in java

Find the last index of a word(string) from a String(paragraph) in java?

String sample="Give your club and/or district the publicity and recognition it deserves! Tell your local community about Toastmasters events, programs and member achievements. Use the news templates below to garner interest and awares are formatted and downloadable as Word documents.Click on a news release and save it to your computer. Localize the news release by replacing the bolded text with your club or district information. Proofread it for accuracy. "

String selectedText = tarea.getSelectedText(); // Select some text from the jTextpane then here -> selectedText = about


I need to find the last index of
selectedtext
not from the
Jtextpane
. I want to find the word(about) in the sample(String)

Answer

use String::lastIndexOf() and String::contains().

According JPane::getSelectedText()

Returns the selected text contained in this TextComponent. If the selection is null or the document empty, returns null.

Check if there is text selected and sum to initial index the length of selectedText to get last char of last occurrence of.

String sample="Give your club and/or district the publicity and recognition it deserves! Tell your local community about Toastmasters events, programs and member achievements. Use the news templates below to garner interest and awares are formatted and downloadable as Word documents.Click on a news release and save it to your computer. Localize the news release by replacing the bolded text with your club or district information. Proofread it for accuracy."
String selectedText = tarea.getSelectedText();
int lastIndex = 0;
int firstIndex = 0;
if (!null.equals(sample) && sample.contains(selectedText)) {
    lastIndex = sample.lastIndexof(selectedText) + selectedText.length;
    firstIndex = sample.lastIndexof(selectedText);
}