Find Nth Occurrence

The third question on the 2017 AP Computer Science Exam had you go through a phrase and replace the Nth occurrence of a string and find the last occurrence. For both of these you were required to use a method called findNthOccurrence , which did not have an implementation shown. Like many AP FRQs you were given an arbitrary method to use, but didn't need to know or care how that method worked.

But let's say you're interested. How might that method be implemented?

While writing a JUnit test for this question I needed an implementation of this method. Here is what I came up with.

public int findNthOccurrence( String str, int n ) {
    int idx = currentPhrase.indexOf( str );
    if ( idx == -1 ) {
        return -1;

    for ( int i = 1; i < n; i++ ) {
        idx = currentPhrase.indexOf( str, idx + 1 );
        if ( idx == -1 ) {
            return -1;
    return idx;

First step is to decide if the substring str is in currentPhrase at all. If it's not the first indexOf will return -1 and we'll go ahead and bail then.

Then we'll start looping at 1 up to n to see if we find that occurrence of str. If we don't find it, again we return -1. If we do find it we return the location as idx.

Why ClassCube?

Are you spending too much time grading your students' source code?

ClassCube is an online tool for Computer Science teachers that allows you to create lab assignments for your students. They'll submit their code online and ClassCube will automatically grade it for you.

Teaching with ClassCube…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>