QuaternionsRock
QuaternionsRock

Reputation: 912

Find char index where contains() found sequence

    if(input.contains("Angle ")) {
        input.charAt(?);
    }

So, basically, how would you find the char directly after "Angle "? In absolute simplest terms, how do you find the indexes in which "Angle " was found?

Upvotes: 5

Views: 1678

Answers (4)

Jason C
Jason C

Reputation: 40315

As others have stated, you may use indexOf to find the location of the substring. If you have more than one occurrence of the substring and you want to find all of them, you can use the version of indexOf that takes a starting position to continue the search after the current occurrence, e.g. to find all occurrences of needle in haystack:

int index = 0;

while ((index = haystack.indexOf(needle, index)) != -1) {
    System.out.println("Found substring at " + index);
    index += needle.length();
} 

Note, by the way, that .contains(needle) is essentially the same as .indexOf(needle) > -1 (in fact, that is precisely how contains() is implemented).

Upvotes: 0

Bohemian
Bohemian

Reputation: 424983

To find the word following "Angle ", you could use regex:

String next = str.replaceAll(".*Angle (\\w+).*", "$1");

Then you don't have to sully yourself with indexes, iteration and lots of code.

Upvotes: 0

sager89
sager89

Reputation: 980

Have you tried the indexOf() method?

From java doc...

Returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that: this.startsWith(str, k) is true.

Then since you know the length of the string, you could add that to the input to find the char directly after "Angle ".

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You can use the indexOf method both to find out that the input contains the string, and where its index is:

int pos = input.indexOf("Angle ");
if (pos >= 0) {
    ... // Substring is found at index pos
}

Upvotes: 3

Related Questions