Home >Java >Find specific word index after given word in String Java

Find specific word index after given word in String Java

WBOY
WBOYforward
2024-02-22 13:40:071094browse

In Java programming, finding the index of a specific word after a given word is a common problem. In the String class, there are multiple methods to achieve this functionality. This article will demonstrate through specific cases how to use these methods in Java to find the target word and obtain its index position. Let us follow the guidance of PHP editor Apple and learn more about this useful technique.

Question content

Suppose I have a string

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

Now I want to write a function in which I pass the entire string, matchingword, wordtofindaftermatchingword

So suppose I want to find the index of "game", but the "game" word should come after the "end" word, and the "end" word can appear n times in the string. I don't want to use regular expressions because I'm thinking of making this function generic.

Solution

As someone said, you can use the method indexof(string,int) with a starting index:

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

Now this:

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

will print 94

The above is the detailed content of Find specific word index after given word in String Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete