首页  >  文章  >  在 String Java 中查找给定单词后的特定单词索引

在 String Java 中查找给定单词后的特定单词索引

WBOY
WBOY转载
2024-02-22 13:40:071027浏览

在Java编程中,查找给定单词后的特定单词索引是一个常见问题。在String类中,有多种方法可以实现这一功能。本文将通过具体案例演示如何在Java中使用这些方法来查找目标单词并获取其索引位置。让我们一起跟随php小编苹果的指导,深入了解这一有用的技巧。

问题内容

假设我有字符串

String str = "Hello all, the world is going to end here and I am the only end character which is in the end game of the end world";

现在我想编写一个函数,在其中传递整个字符串、matchingword、wordtofindaftermatchingword

所以假设我想找到“game”的索引,但是“game”单词应该在“end”单词之后,并且“end”单词可以在 string 中出现 n 次。我不想使用正则表达式,因为我正在考虑使这个函数通用。

解决方法

正如有人所说,您可以使用带有起始索引的方法indexof(string,int):

public static int indexof(string str, string word, string precededby) {
    int i = str.indexof(precededby);
    if (i < 0) {
        return -1;
    }
    return str.indexof(word, i+precededby.length());
}

现在这个:

System.out.println(indexOf(str, "game", "end"));

将打印 94

以上是在 String Java 中查找给定单词后的特定单词索引的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除