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.
📄 Table of Contents
💻 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:
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
}
}
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:
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
}
}
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:
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
}
}
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.
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
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
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())
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
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.
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)
int count=0;
for(int i=0;i if(s.charAt(i)=='l') count++;
return count;
String r="";
String s="abcde";
for(int i=0;i r+=s.charAt(i);
System.out.println(r);
String r="";
for(int i=s.length()-1;i>=0;i--)
r+=s.charAt(i);
return r;
❓ Frequently Asked Questions
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.
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.
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.
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.
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.
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
🔗 Related Topics
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]