---
title: "replaceNthOccurrence — AP CSA Definition & FRQ Guide"
description: "replaceNthOccurrence swaps the nth match of a substring in a phrase, leaving it unchanged if no nth match exists. A 2017 AP CSA FRQ classic from Topic 2.10."
canonical: "https://fiveable.me/ap-comp-sci-a/key-terms/replacenthoccurrence"
type: "key-term"
subject: "AP Computer Science A"
unit: "Unit 2"
---

# replaceNthOccurrence — AP CSA Definition & FRQ Guide

## Definition

replaceNthOccurrence is a string algorithm from the 2017 AP CSA FRQ (Phrase class) that replaces the nth occurrence of a substring with a replacement string, rebuilt using substring and concatenation, and leaves the phrase unchanged if fewer than n occurrences exist.

## What It Is

replaceNthOccurrence is a [method](/ap-comp-sci-a/unit-3/abstraction-and-program-design/study-guide/o9VgVeIpKRYZ7N7rXfUz "fv-autolink") from the 2017 [AP Computer Science A](/ap-comp-sci-a "fv-autolink") free-response exam (Question 3, the Phrase class). The Phrase class stores a string called currentPhrase, and your job was to write a method that finds the nth time a given substring shows up and swaps just that one occurrence for a replacement string. If the substring doesn't appear n times, the phrase stays exactly as it was.

The [algorithm](/ap-comp-sci-a/key-terms/algorithm "fv-autolink") itself is a classic Topic 2.10 pattern. You don't edit a String in place (Strings are immutable in Java). Instead, you find the index of the nth occurrence, then build a brand-new string by gluing together three pieces: everything before the match, the replacement text, and everything after the match. The 'do nothing if it's not there' rule is the part that catches people. It forces you to check the result of your search before you rebuild, usually by testing whether the index equals -1.

## Why It Matters

This term lives in **[Unit 2](/ap-comp-sci-a/unit-2 "fv-autolink"): Selection and Iteration**, specifically **Topic 2.10: Developing Algorithms Using Strings**. It directly supports learning objective **2.10.A**, which asks you to develop code for standard and original string algorithms and determine their results. EK 2.10.A.1 calls out finding substrings with a particular property and counting substrings that meet criteria, and replaceNthOccurrence is exactly that skill with one extra step (rebuilding the string). It also bundles together almost everything Unit 2 tests at once: a [loop](/ap-comp-sci-a/key-terms/loop "fv-autolink") to search, an if statement to guard against the missing case, and substring plus concatenation to produce the answer. That's why it makes such a good FRQ.

## Connections

### [Sentinel value (Unit 2)](/ap-comp-sci-a/key-terms/sentinel-value)

[indexOf](/ap-comp-sci-a/key-terms/indexof "fv-autolink") returns -1 when a substring isn't found, and -1 is a sentinel value, a special 'stop, nothing here' signal. The 'preserve the original phrase' rule in replaceNthOccurrence is really just a sentinel check. If your search comes back -1, you return without touching anything.

### [Overlapping occurrences (Unit 2)](/ap-comp-sci-a/key-terms/overlapping-occurrences)

Where you restart the search after each match decides whether occurrences can overlap. Restarting one character past the start of the last match allows overlaps; restarting after the whole match doesn't. Misjudging this gives you the wrong 'nth' occurrence, so your replacement lands in the wrong spot.

### While loops and string traversal (Unit 2)

Finding the nth occurrence means calling indexOf repeatedly in a loop, moving your starting position forward each time. It's the same search-and-advance [pattern](/ap-comp-sci-a/unit-1/why-programming-why-java/study-guide/lVK6rmrBuug17i1Hna9z "fv-autolink") behind counting substrings, the standard algorithm EK 2.10.A.1 names directly.

## On the AP Exam

This is straight from 2017 FRQ Q3, which gave you the Phrase class and asked you to analyze and modify the string it stored. To earn the points, you had to do three things in order. First, locate the nth occurrence (the class provided a findNthOccurrence helper, and using given helpers instead of rewriting them is a real scoring habit). Second, check for the not-found case and leave currentPhrase alone if the nth occurrence doesn't exist. Third, rebuild the phrase with substring calls and concatenation, being careful that the second substring starts at the found index plus the length of the string being replaced, not plus the length of the replacement. In multiple choice, this same logic shows up as 'what does this code print' questions where the trap answers come from off-by-one substring indices or forgetting the -1 guard.

## replaceNthOccurrence vs String's built-in replace method

Java's built-in str.replace(old, new) swaps EVERY occurrence at once. replaceNthOccurrence swaps exactly one, the nth, and leaves the rest alone. That's the whole point of the FRQ. You can't lean on replace; you have to find the right index yourself and rebuild the string around it with substring and concatenation.

## Key Takeaways

- replaceNthOccurrence comes from the 2017 AP CSA FRQ (Phrase class) and replaces only the nth occurrence of a substring, not all of them.
- If the substring appears fewer than n times, the method leaves currentPhrase completely unchanged, and you handle that by checking for -1 before rebuilding.
- Strings are immutable in Java, so you replace by building a new string: the part before the match, plus the replacement, plus the part after the match.
- The second substring call must start at the match index plus the length of the OLD string, not the replacement string. That's the most common off-by-one error.
- This algorithm supports LO 2.10.A by combining iteration (searching for occurrences), selection (the not-found guard), and string building in one method.
- On FRQs, use helper methods the class already gives you, like findNthOccurrence, instead of rewriting the search from scratch.

## FAQs

### What is replaceNthOccurrence in AP Computer Science A?

It's a method from the 2017 AP CSA FRQ Q3 (the Phrase class) that replaces the nth occurrence of a given [substring](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW "fv-autolink") in currentPhrase with a replacement string. If the substring doesn't appear n times, the phrase is left unchanged.

### Can I just use Java's replace method to write replaceNthOccurrence?

No. str.replace(old, new) replaces every occurrence, but this method must replace only the nth one. You have to find the index of that specific occurrence and rebuild the string with substring and concatenation.

### How is replaceNthOccurrence different from findNthOccurrence?

findNthOccurrence only searches. It returns the index of the nth match, or -1 if there isn't one. replaceNthOccurrence uses that index to actually change the phrase by building a new string with the replacement spliced in.

### What happens in replaceNthOccurrence if the nth occurrence doesn't exist?

Nothing. The original phrase is preserved. In code, that means checking whether your search returned -1 (a sentinel value) and returning without modifying currentPhrase.

### Why is replaceNthOccurrence tricky to code on the AP exam?

Two reasons. The 'after the match' substring must start at the index plus the length of the string being replaced (not the replacement's length), and you have to guard the not-found case so the phrase isn't changed when fewer than n occurrences exist.

## Related Study Guides

- [2.10 Developing Algorithms Using Strings](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW)

## Structured Data

```json
{"@context":"https://schema.org","@graph":[{"@type":"LearningResource","@id":"https://fiveable.me/ap-comp-sci-a/key-terms/replacenthoccurrence#resource","name":"replaceNthOccurrence — AP CSA Definition & FRQ Guide","url":"https://fiveable.me/ap-comp-sci-a/key-terms/replacenthoccurrence","learningResourceType":"Concept explainer","educationalLevel":"AP® / High School","about":{"@id":"https://fiveable.me/ap-comp-sci-a/key-terms/replacenthoccurrence#term"},"audience":{"@type":"EducationalAudience","educationalRole":"student"},"dateModified":"2026-06-11T05:27:19.614Z","isPartOf":{"@type":"Collection","name":"AP Computer Science A Key Terms","url":"https://fiveable.me/ap-comp-sci-a/key-terms"},"publisher":{"@type":"Organization","name":"Fiveable","url":"https://fiveable.me"}},{"@type":"DefinedTerm","@id":"https://fiveable.me/ap-comp-sci-a/key-terms/replacenthoccurrence#term","name":"replaceNthOccurrence","description":"replaceNthOccurrence is a string algorithm from the 2017 AP CSA FRQ (Phrase class) that replaces the nth occurrence of a substring with a replacement string, rebuilt using substring and concatenation, and leaves the phrase unchanged if fewer than n occurrences exist.","url":"https://fiveable.me/ap-comp-sci-a/key-terms/replacenthoccurrence","inDefinedTermSet":{"@type":"DefinedTermSet","name":"AP Computer Science A Key Terms","url":"https://fiveable.me/ap-comp-sci-a/key-terms"}},{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is replaceNthOccurrence in AP Computer Science A?","acceptedAnswer":{"@type":"Answer","text":"It's a method from the 2017 AP CSA FRQ Q3 (the Phrase class) that replaces the nth occurrence of a given [substring](/ap-comp-sci-a/unit-2/developing-algorithms-using-strings/study-guide/hDOL1VhnMQFPkBf6xMMW \"fv-autolink\") in currentPhrase with a replacement string. If the substring doesn't appear n times, the phrase is left unchanged."}},{"@type":"Question","name":"Can I just use Java's replace method to write replaceNthOccurrence?","acceptedAnswer":{"@type":"Answer","text":"No. str.replace(old, new) replaces every occurrence, but this method must replace only the nth one. You have to find the index of that specific occurrence and rebuild the string with substring and concatenation."}},{"@type":"Question","name":"How is replaceNthOccurrence different from findNthOccurrence?","acceptedAnswer":{"@type":"Answer","text":"findNthOccurrence only searches. It returns the index of the nth match, or -1 if there isn't one. replaceNthOccurrence uses that index to actually change the phrase by building a new string with the replacement spliced in."}},{"@type":"Question","name":"What happens in replaceNthOccurrence if the nth occurrence doesn't exist?","acceptedAnswer":{"@type":"Answer","text":"Nothing. The original phrase is preserved. In code, that means checking whether your search returned -1 (a sentinel value) and returning without modifying currentPhrase."}},{"@type":"Question","name":"Why is replaceNthOccurrence tricky to code on the AP exam?","acceptedAnswer":{"@type":"Answer","text":"Two reasons. The 'after the match' substring must start at the index plus the length of the string being replaced (not the replacement's length), and you have to guard the not-found case so the phrase isn't changed when fewer than n occurrences exist."}}]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"AP Computer Science A","item":"https://fiveable.me/ap-comp-sci-a"},{"@type":"ListItem","position":2,"name":"Key Terms","item":"https://fiveable.me/ap-comp-sci-a/key-terms"},{"@type":"ListItem","position":3,"name":"Unit 2","item":"https://fiveable.me/ap-comp-sci-a/unit-2"},{"@type":"ListItem","position":4,"name":"replaceNthOccurrence"}]}]}
```
