Home > Java > body text

Find specific word index after given word in String Java

WBOY
Release: 2024-02-22 13:40:07
forward
1025 people have browsed it

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";
Copy after login

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

Now this:

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

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!