Momo Lakers
Momo Lakers

Reputation: 9

How to get the index of second or nth occurencece of a char without array only string class in JAVA

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

Answers (2)

Alexey Novik
Alexey Novik

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

Matt Cramblett
Matt Cramblett

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

Related Questions