AP CSA String Algorithms

String Algorithms in AP CSA: Complete Guide (2025-2026)

String algorithms in AP CSA combine Unit 1 String methods with Unit 2 loop patterns to solve character-level problems, and they appear on every AP Computer Science A exam as both MCQ trace questions and FRQ method implementations (25–35%). The four core String algorithm patterns are: counting (how many characters meet a condition), scanning (searching for a character or pattern using indexOf), building (constructing a new String one character at a time), and substring loops (processing substrings of fixed or variable length). Mastering these patterns and their interaction with charAt, substring, and length is the key to String FRQ success.

💻 Code Examples — Predict First

Before running each example, write down your prediction. This is the single most effective AP exam study technique.

🤔 Predict the output before running:

Example 1: Count and Build Patterns
public class Main {
    // COUNT: characters meeting a condition
    public static int countUpper(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 'A' && c <= 'Z') {
                count++;
            }
        }
        return count;
    }
    // BUILD: construct new String
    public static String removeSpaces(String s) {
        String result = "";
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != ' ') {
                result += s.charAt(i);
            }
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(countUpper("Hello World"));  // 2
        System.out.println(removeSpaces("AP CSA"));     // APCSA
    }
}
Running…

2 / APCSA — COUNT: loop over each char, increment when condition met. BUILD: initialize result="", append qualifying chars. Uppercase check: 'A'<=c<='Z' using char comparison.

🤔 Predict the output before running:

Example 2: Scan with indexOf and Reverse
public class Main {
    // SCAN with indexOf: find all occurrences
    public static int countOccurrences(String text, String target) {
        int count = 0;
        int index = text.indexOf(target);
        while (index != -1) {
            count++;
            index = text.indexOf(target, index + 1);
        }
        return count;
    }
    // REVERSE BUILD
    public static String reverse(String s) {
        String result = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            result += s.charAt(i);
        }
        return result;
    }
    public static void main(String[] args) {
        System.out.println(countOccurrences("banana", "an")); // 2
        System.out.println(reverse("hello"));                 // olleh
    }
}
Running…

2 / olleh — SCAN: use indexOf in a while loop, advancing start position each time. indexOf returns -1 when not found — that’s the exit condition. REVERSE BUILD: loop from length-1 down to 0.

🤔 Predict the output before running:

Example 3: Substring Loops and Early-Exit Check
public class Main {
    // SUBSTRING LOOP: process fixed-length substrings
    public static void printPairs(String s) {
        for (int i = 0; i < s.length() - 1; i++) {
            System.out.print(s.substring(i, i + 2) + " ");
        }
        System.out.println();
    }
    // CHECK: does string contain only digits?
    public static boolean allDigits(String s) {
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c < '0' || c > '9') {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        printPairs("hello");          // he el ll lo
        System.out.println(allDigits("12345"));  // true
        System.out.println(allDigits("12a45"));  // false
    }
}
Running…

he el ll lo / true / false — SUBSTRING LOOP: i from 0 to length-2 (one less than length to avoid out-of-bounds on substring(i, i+2)). ALL-CHECK: return false at the first non-qualifying char, return true only if loop completes.

❌ Common Pitfalls

These are the mistakes students most often make on the AP CSA exam with String algorithms AP CSA counting scanning building. Study them carefully.

1
⚠ Off-by-one in substring loop: going to length instead of length-1

When processing pairs or overlapping substrings of size k, the loop must stop at length - k, not length. For pairs (k=2), stop at length - 1. Going to length causes StringIndexOutOfBoundsException.

// Pairs (k=2): stop at length-1
for(int i=0; i
  
2
⚠ Forgetting to initialize result string before the build loop

The result String must be initialized to an empty String "" before the loop. Declaring it inside the loop or leaving it uninitialized resets it every iteration or causes a compile error.

String result; // uninitialized -- compile error in loop
String result = ""; // CORRECT: initialize before loop
3
⚠ Using index + target.length() instead of index + 1 in indexOf scan

To find ALL occurrences including overlapping ones, advance by 1: index + 1. To find only non-overlapping occurrences, advance by the target length: index + target.length(). Choose based on the problem.

// overlapping: indexOf("aa", index+1)
// non-overlapping: indexOf("aa", index + target.length())
4
⚠ Comparing chars with .equals() instead of ==

Characters (the primitive char) are compared with ==, not .equals(). charAt() returns a char primitive, so c == 'a' is correct. Using c.equals('a') is a compile error (char is not an object).

char c = s.charAt(i);
c == 'a'       // CORRECT: char comparison
c.equals('a')  // COMPILE ERROR: char is primitive
🎓 AP Exam Tip

On the AP FRQ, String algorithm methods follow this template: declare variables (result String or counter), loop from 0 to length()-1, use charAt(i) or substring(i, i+k), apply condition, update result, return after loop. Write this skeleton first, then fill in the condition.

⚠ Watch Out!

For the all-match check pattern (is every character a digit? is every character uppercase?): use early return false when you find the first non-qualifying char, and return true only after the loop completes. This is both efficient and earns full FRQ credit.

✍ Check for Understanding (8 Questions)

Your Score: 0 / 0
1. What does this method return for s = "Hello World"?
int count=0;
for(int i=0;i if(s.charAt(i)=='l') count++;
return count;
2. Which loop correctly builds a String of only the vowels in s?
3. For s = "banana", what does countOccurrences(s, "a") return?
4. Why does the substring loop stop at s.length()-1 instead of s.length()?
5. What is the correct pattern to check if ALL characters in s are letters?
6. What is printed?
String r="";
String s="abcde";
for(int i=0;i r+=s.charAt(i);
System.out.println(r);
7. When using indexOf in a while loop, what is the exit condition?
8. What is the output of reverse("Java")?
String r="";
for(int i=s.length()-1;i>=0;i--)
r+=s.charAt(i);
return r;

❓ Frequently Asked Questions

What are the four core String algorithm patterns in AP CSA?

Count (how many chars meet condition), Build (construct new String char by char), Scan with indexOf (find occurrences), and Substring loops (process fixed-length substrings). Most AP FRQ String methods use one or two of these.

How do I build a new String in a loop?

Initialize an empty String before the loop: String result = "". Inside the loop, append qualifying characters: result += s.charAt(i). Return result after the loop. Never initialize inside the loop or the result resets every iteration.

How do I count all occurrences of a substring?

Use a while loop with indexOf: int index = text.indexOf(target); while (index != -1) { count++; index = text.indexOf(target, index + 1); }. The index + 1 advances past the current match to find the next one.

Why do I compare characters with == instead of .equals()?

charAt() returns a char, which is a primitive type in Java. Primitive types are compared with ==. The .equals() method only works on objects. Calling .equals() on a char is a compile error.

How do I check if every character in a String meets a condition?

Use early-exit return false: loop through every character, return false immediately when you find a character that doesn't meet the condition. Return true only after the loop completes without finding any violations.

TC

Tanner Crow — AP CS Teacher & Tutor

11+ years teaching AP Computer Science at Blue Valley North High School (Overland Park, KS). Verified Wyzant tutor with 1,845+ hours, 451+ five-star reviews, and a 5.0 rating. His AP CSA students score 5s at more than double the national rate.

  • 54.5% of students score 5 on AP CSA (national avg: 25.5%)
  • 1,845+ verified tutoring hours • 5.0 rating
  • Free 1-on-1 tutoring inquiry: Wyzant Profile

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]