2.10 Implementing String Algorithms
Traverse a String with a loop and substring to search, count, reverse, and build new Strings.
- 1. LxD Cycle Process
- 2. Lesson Plan
- 3. Reference Guide
- 4. Code Examples
- A. Simple: String Algorithms in Code
- Code Runner Challenge
- 5. Hacks & Practice Tasks
- 6. Grading Plan (1 Point Total)
- 7. Lesson Revisions & Feedback Evidence
- 8. Summary
- 9. References
1. LxD Cycle Process
Empathize: Students write traversals that run one position too far and crash, because the last valid index is one less than the length and that gap is easy to forget.
Define:
- POV: CSA students need to set loop bounds from
length()deliberately, because an out of bounds traversal fails at run time rather than at compile time. - Learning Goal: Students will traverse Strings with a loop, take one character windows with
substring, build new Strings, and set bounds that stay inside the String.
Ideate:
- HMW Question: How might we make the boundary between the last valid index and the crash visible before students hit it?
- Activity: A reverse-a-String walkthrough, a bounds and bugs activity, and a count-the-passes exercise.
Prototype & Test: Activity 3 is built around bounds specifically, because the out of bounds error is the failure that this topic produces most often.
2. Lesson Plan
Learning Objective: Develop algorithms that traverse String objects.
Success Criteria: You can traverse a String with a loop, use substring to take a one character window, and build a new String without running past either end.
Tech Talk & Introduction (5 minutes)
A String traversal is a for loop over the positions of the String.
length()gives the number of characters. Valid positions run from0tolength() - 1.substring(i, i + 1)takes the single character at positioni.- Build a new String by starting with
""and concatenating inside the loop. - Going past
length() - 1throwsStringIndexOutOfBoundsException, which is the most common runtime error in this topic.
3. Reference Guide
Key Ideas
- A String has positions (indexes) from
0tolength() - 1. s.substring(i, i + 1)is the single character at indexi. Traverse a String with aforloop overi.s.substring(i, i + k)is a window ofkcharacters starting ati. The window must fit:i + k <= s.length(), so loop whilei <= s.length() - k.- Compare Strings with
.equals, never==. - Build a new String by starting with
""and adding pieces with+. - Standard algorithms: count a character, find or count a substring, reverse, check a palindrome.
Methods You Will Use
| Method | Meaning | Example (s = "iterate") |
|---|---|---|
s.length() |
number of characters | 7 |
s.substring(2, 5) |
characters at 2, 3, 4 (stops before 5) | "era" |
s.substring(4) |
from index 4 to the end | "ate" |
s.indexOf("ra") |
index of the first match, or -1 | 3 |
s.equals(t) |
same characters? | true or false |
- Going past the end throws a
StringIndexOutOfBoundsException. Check the loop bounds first.
4. Code Examples
A. Simple: String Algorithms in Code
Run the program. Then change word and sub and confirm the search still finds matches at the very end of the String.
Code Runner Challenge
Sliding window search with correct bounds, plus counting a substring.
View IPYNB Source
// CODE_RUNNER: Sliding window search with correct bounds, plus counting a substring.
public class StringFinder {
public static void main(String[] args) {
String word = "iterate";
String sub = "rate";
boolean found = false;
// The window must fit, so the last start index is word.length() - sub.length()
for (int i = 0; i <= word.length() - sub.length(); i++) {
String window = word.substring(i, i + sub.length());
if (window.equals(sub)) {
found = true;
System.out.println("Found \"" + sub + "\" at index " + i);
}
}
if (!found) {
System.out.println("\"" + sub + "\" is not in \"" + word + "\"");
}
// Count how many windows of length 2 appear in the word
int count = 0;
String pair = "te";
for (int i = 0; i <= word.length() - pair.length(); i++) {
if (word.substring(i, i + pair.length()).equals(pair)) {
count++;
}
}
System.out.println("\"" + pair + "\" appears " + count + " times");
}
}
StringFinder.main(null);
5. Hacks & Practice Tasks
Prepare your submission IPYNB
- Create a new notebook in your portfolio homework area:
_notebooks/homework. - Add one markdown cell at the top with the frontmatter:
---
layout: post
title: CSA Unit 2.10 Implementing String Algorithms HW
categories: [Java, String-Algorithms]
lesson_language: Java
lesson_topic: String-Algorithms HW
lesson_source: APCSA
lesson_type: lesson
permalink: /csa/unit_02/2_10_hw
author: yourGithubID
---
- Add code cells for the Popcorn Hack and the Homework Hack. Ensure all code runs and output is visible.
- Include a markdown cell before each code section explaining the concept.
Submission Safety Rules (Read First)
[IMPORTANT] To avoid grading errors, follow these rules exactly:
- Write your prediction before you run each code section
- Execute every code cell and leave the output visible
- Show your work for any hand-traced prediction
- Do not just copy code; explain what each line does
- Label each question clearly
Activity 1: Sliding Window Search
The window is the same length as sub. It slides one index at a time and stops when it can no longer fit. Try sub = ate to see a match at the very end, and sub = xyz for no match.
Activity 2: Reverse a String
Build a new String one character at a time. Notice the new character goes in front of what was built so far.
Activity 3: Bounds and Bugs
What does this print?
word is "iterate" and sub is "rate". What happens?
Which loop counts how many times the letter a appears in s?
Activity 4: Count the Passes
word.length() is 7 and sub.length() is 3. How many times does the body of for (int i = 0; i <= word.length() - sub.length(); i++) run?
What is "computer".substring(3, 6)? Type the characters only.
Popcorn Hack (In-Class)
Count the vowels in word. Use a one character window and a compound Boolean expression with ||. Expected for iterate: 4.
Code Runner Challenge
Popcorn hack: count vowels with substring and
View IPYNB Source
// CODE_RUNNER: Popcorn hack: count vowels with substring and ||. Expected: 4.
public class VowelCounter {
public static void main(String[] args) {
String word = "iterate";
int vowels = 0;
// TODO: for each index i, take word.substring(i, i + 1)
// and count it if it equals a, e, i, o, or u
System.out.println("Vowels: " + vowels); // expected: 4
}
}
VowelCounter.main(null);
Homework Hack
Two short tasks.
- Finish the runner:
isPalindromereturnstruewhen a String reads the same backwards. Build the reversed String, then compare with.equals. - Answer the quick check.
Code Runner Challenge
Homework: palindrome check with a reversed String and equals.
View IPYNB Source
// CODE_RUNNER: Homework: palindrome check with a reversed String and equals.
public class Palindrome {
public static boolean isPalindrome(String s) {
String rev = "";
// TODO: build rev by adding each character to the front
// TODO: return whether rev equals s
return false;
}
public static void main(String[] args) {
System.out.println("racecar: " + isPalindrome("racecar")); // true
System.out.println("level: " + isPalindrome("level")); // true
System.out.println("java: " + isPalindrome("java")); // false
}
}
Palindrome.main(null);
What does this print?
6. Grading Plan (1 Point Total)
Classroom Rubric
-
0.2 points: Popcorn completion Student counted the vowels in
wordusing a one character window and a compound condition with||, printing 4 foriterate. -
0.8 points: Homework completion
- 0.5 Palindrome:
isPalindromebuilds the reversed String and compares with.equals, returning correct results for a palindrome and a non-palindrome. - 0.2 Quick check: The traversal question is answered with the index range stated.
- 0.1 Notebook quality: Every code cell executed with output visible, and a markdown cell before each code section explaining the concept.
- 0.5 Palindrome:
Quick Validation Checklist
- Present: loop bound derived from
length() - Present:
.equalsused for the String comparison - Absent: any index that can reach
length() - Test:
iterateyields 4 vowels;racecaris a palindrome andjavais not
7. Lesson Revisions & Feedback Evidence
Feedback Received: Team review of the Unit 2 set found that these lessons did not follow the section format used by the Unit 1 lessons, and that they ended without the assignment submission form every other CSA lesson provides.
Revision Made: The lesson was reorganised into the shared CSA lesson format, so it now opens with the LxD cycle and lesson plan, states its reference material before the code, and groups the activities, Popcorn Hack and Homework Hack under one practice section. The duplicate lesson heading was removed, and the page now renders the standard Submit Assignment form at the end.
Design Decision Kept: Activity 3 is built around bounds specifically, because the out of bounds error is the failure that this topic produces most often.
Open Item: Record peer feedback from the team teach delivery here once the lesson has been taught.
8. Summary
- Traverse with
for (int i = 0; i < s.length(); i++)andsubstring(i, i + 1). - A window of length
kneedsi <= s.length() - k. .equalsfor comparisons,+to build new Strings.- Reverse by putting each new character in front; palindrome means
rev.equals(s). - Next lesson: loops inside loops.
9. References
College Board Course and Exam Description
Topic 2.10, Implementing String Algorithms, is required content on the AP Computer Science A Exam. The objective quoted in section 2 of this lesson is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.
Outside Academic Reference
String positions are zero-based and substring takes a start index and an exclusive end index, which is why a one character window is written as substring(i, i + 1) and why the last valid start index is one less than the length.
Reference List
College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/courses/ap-computer-science-a
Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java language specification: Java SE 21 edition. Oracle America. https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html
Submit Assignment
Need to update a submission later? Open the submissions dashboard.