Christian A
Christian A

Reputation: 501

Find index of substring, from before known index

I have a hard time thinking about a descriptive title, so sorry for that.

I'm facing an issue here. I have a lot of code files that I have to manipulate. And I have to find some indexes in order to get a substring. Here is an example:

public BigInteger getGenbestillingerTilbageKvantitet() {
        return genbestillingerTilbageKvantitet;
    }

I have to be able to locate the starting index of the above example (I have the entire code file, loaded as a string, so the method shown would be a substring of the entire code file). I'm able to get the index of getGenbestillingerTilbageKvantitet(), because I have "GenbestillingerTilbageKvantitet" in an array (along with others):

int index7 = fileContent.indexOf("get" + capitalizedProps[i])

This is how I do it.

Then I would find the end of the method like this:

int index4 = fileContent.indexOf("}", index3) + 1

The issue is that i need the index of "public". But since the type is not nessecarily "BigInteger" it gives me some trouble.

Does anyone know how to get the index from public? If the type were of a custom type, I could do:

String s = "public " + capitalizedProps[i] + "Type get" + capitalizedProps[i]
int index3 = fileContent.indexOf(s)

Which works sometimes :) But not when the type is BigInteger or even String.

Upvotes: 1

Views: 226

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

If you want to get the index of the public keyword preceding getGenbestillingerTilbageKvantitet method name then you can use String.lastIndexOf(str) of the substring created from the beginning up to index of getGenbestillingerTilbageKvantitet method name. Something like this:

int pubKeyIdx = fileContent.substring(0, index7).lastIndexOf("public")

where index7 variable holds the index of the method name.

Upvotes: 1

Related Questions