Reputation: 9
am trying to make a method in Java that give me the index of nth occurence of a char in a String. example String Hello="allo every body how are you" How can I get the index of the 3rd 'Y'? thank you
Upvotes: 0
Views: 67
Reputation: 16
public static int findIndex(String string, char c, int n)
{
int len = string.length();
return IntStream.range(0, len)
.filter(i -> c == string.charAt(i))
.skip(n-1)
.findFirst()
.orElse(-1); // No element found
}
Upvotes: 0
Reputation: 41
final String text = "allo every body how are you";
int n = 3;
final char toFind = 'y';
int index = 0;
while (index < text.length()) {
if (text.charAt(index) == toFind) {
n--;
if (n == 0)
break;
}
index++;
}
// index is 24
System.out.print(index);
Upvotes: 1