查找给定单词之后的下一个单词的索引

问题描述 投票:0回答:1

我正在尝试编写一个函数,如果我传递一个字符串、单词、nextWord,如果匹配 else -1,它应该返回 nextWord 的索引。

假设我有绳子

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."

在函数中我将传递 String s、word="everywhere"、nextWord="and"。如果“and”位于“everyWhere”之后(如上面的字符串所示),则返回“and”的索引,否则返回 -1。

不想使用正则表达式。

尝试过的示例代码

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());
    }

在上面的代码中,如果我传递下面的示例字符串,其中单词“and”不在“everywhere”之后

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."

词=“和” nextWord =“无处不在”

代码返回索引为 158,而它应该返回 -1,因为在字符串中“everywhere”后面没有“and”

java substring indexof
1个回答
0
投票

您需要修改您的函数以正确检查下一个单词是否出现在该单词之后。做法应该是先找到单词的索引,然后检查下一个单词是否紧随其后。

public static int indexOfPreceded(String str, String word, String nextWord) {
    int wordIndex = str.indexOf(word);
    
    if (wordIndex < 0) {
        return -1; 
    }
    
    int nextWordIndex = str.indexOf(nextWord, wordIndex + word.length());
    
    if (nextWordIndex == wordIndex + word.length()) {
        return nextWordIndex; 
    } else {
        return -1; 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.