This only works because
int index = inp.indexOf("A");
returns the index of the first occurrence of A, beginning with the 0th character (inclusive). (See the documentation here.) If you set a second argument
int index = inp.indexOf("A", 5);
indexOf
will only return the first A that it finds at or after index 5
.
What you are doing is
int index = inp.indexOf("A", inp.indexOf("A")+1);
...which finds the first occurrence of "A", then moves to the next character in the String, then looks for the second occurrence of "A". This will only work if there are multiple "A" in the String.
Suppose you have a String like
String phil = "ABACAB";`
Then phil.indexOf("A")
returns 0
, and phil.indexOf("A", phil.indexOf("A")+1)
simplifies to phil.indexOf("A", 0+1)
or just phil.indexOf("A", 1)
. So you're looking for the first occurrence of "A" at or after the 1st index (the first "B" in "ABACAB"). This will return 2
.
Doing something like:
int index = inp.indexOf("A", inp.indexOf("A")+2);
Does the same thing, but moves forward two characters, after finding the first occurrence of "A". So for our example, this simplifies to phil.indexOf("A", 2)
, which will return 2
, finding the same, second "A" that it found in the first case.
To find the third occurrence, you need to chain the calls, as you noted:
int index = inp.indexOf("A", inp.indexOf("A", inp.indexOf("A")+1)+1);
Or use a third-party library.