0
public static int getNthOccurrence(int n, char find, String str)
    {
        int counter=0;
        for(int i=0;i<str.length();i++)
        {
            if(str.charAt(i)==find)
            {
                counter++;
                if(counter==n)
                    return i;
            }
        }
        return -1;
    }

I have already seen this thread Java: method to get position of a match in a String?

The code runs that:

int n=getNthOccurrence(3,'n',"you arent gonna find me");

output: 13

2 Answers2

0

Once you've changed the parameter type to String:

public static int getNthOccurrence(int n, String find, String str)

Use String.indexOf(String, int):

i = -find.length();
for (int count = 0; count < n; ++count) {
  i = str.indexOf(find, i + find.length());
  if (i < 0) break;
}
return (i >= 0) ? i : -1;

(Note that String.indexOf(char, int) is a preferable way to do it with char, as in the case of the original code).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

You can make a char into a String by simply doing this

String theString = yourChar + "";

Your code could look something like this !spoiler below!

public static int getNthOccurrence(int n, char find, String str)
    {

        String f = find + "";
        int counter = 0;

        for (String c : str.split("")){

            if (c.equals(f)) n--;
            if (n < 1 ) return counter;
            counter++;
        }

        return -1;
    }
}
  • I'm not convinced that this is quite what OP meant, because this offers no advantage over the current way. Moreover, this is just a poor approach: don't split `str`, just iterate over the indices and use `str.regionMatches(i, f, 0, f.length())`. – Andy Turner Dec 17 '17 at 20:14
  • What makes the approach poor? – adihrustic Dec 17 '17 at 20:42
  • Splitting the string to iterate it character-by-character. – Andy Turner Dec 17 '17 at 20:45
  • Yes, why is that poor? – adihrustic Dec 17 '17 at 20:48
  • Because you can iterate it character-by-character using `str.charAt`. Converting everything to a string requires you to create a string per character, as well as an array to hold the strings; but it's unnecessary because the only operation you do (equals, on a string that is always 1 char long) can be done equivalently with chars. – Andy Turner Dec 17 '17 at 20:53