I am trying to write a Java function with the following parameters:
String str: the sample textString word: a wordString nextWord: another word
If I pass a given str, a word, and nextWord parameters, it should return me the index of first occurrence of nextWord calculated from the word word, if there are any, otherwise it should return -1.
Suppose I have the following String for the 1st parameter:
String s = "Hatred was spreading everywhere, blood was being spilled everywhere, wars were breaking out everywhere and dinosaurs are everywhere, but please note I want the first and index.";
In the function I will pass String s as the value of str parameter, "everywhere" literal for word, and "and" liter for nextWord, respectively.
If "and" is just after "everyWhere" as in the above String, it returns me the index of "and", otherwise it returns -1.
I would like to avoid using Regex.
I tried with the following sample code:
public static int indexOfPreceded(String str, String word, String nextWord) {
int i = StringUtils.indexOfIgnoreCase(str, nextWord);
if (i < 0) {
return -1;
}
return StringUtils.indexOfIgnoreCase(str, word, i + nextWord.length());
}
Executing the code above, with the following str parameter (where the word "and" is not after "everywhere"), "and" for word, and
"everywhere" for nextWord:
String s = "Hatred was spreading everywhere, blood was being spilled everywhere, wars were breaking out everywhere dinosaurs are everywhere, but please note I want the first and index.";
Since in the String s, there is no "and" before "everywhere", I expect -1 as result, but my function returns 158 as the index.
You need to modify your function to properly check if the nextWord appears just after the word. The approach should be to find the index of the word first, and then check if the nextWord immediately follows it.