Phrase is #3 from the from the 2017 AP Computer Science A Free Response problems.

https://secure-media.collegeboard.org/ap/pdf/ap-computer-science-a-frq-2017.pdf

Part (a) replaceNthOccurrence method

public void replaceNthOccurrence(String str, int n, String repl)
{
    int index = findNthOccurrence(str, n);

    if(index != -1)
    {
        currentPhrase = currentPhrase.substring(0, index) + repl +
                currentPhrase.substring(index + str.length());
    }
}

See Strings on the AP CS A Exam for an explanation of String methods used on the AP CS A Exam.

Part (b) findLastOccurrence method (considered solution)

public int findLastOccurrence(String str)
{
    int n = 1;
    int index = -1;
    int nextIndex = findNthOccurrence(str, n);

    while(nextIndex != -1)
    {
        index = nextIndex;
        n++;
        nextIndex = findNthOccurrence(str, n);
    }

    return index;
}

This is my considered solution using the method from part (a). This solution has the advantage of not running findNthOccurrence an extra time. The solution I wrote under time constraints is farther down.

Part (b) findLastOccurrence method (solution outside Exam)

public int findLastOccurrence(String str)
{
    return currentPhrase.lastIndexOf(str);
}

This solution uses the lastIndexOf method, which isn’t in the AP Java Subset. This is what I would write if I had to perform this task as part of an actual program.

To clarify, this solution is not acceptable on the Exam because the question requires the use of the method from part (a).

Part (b) findLastOccurrence method (initial solution)

public int findLastOccurrence(String str)
{
    int n = 1;
    while(findNthOccurrence(str, n) != -1)
        n++;

    if(n == 1)
        return -1;

    return findNthOccurrence(str, n - 1);
}

This was my solution under time constraints the first time I saw the problem.

2017 AP CS Exam Free Response Solutions

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Phrase