How do you traverse a String with a loop to count, search or transform its characters?
Topic 4.3 Developing Algorithms Using Strings: traverse a String with a loop using length, substring and indexOf to implement standard algorithms such as counting characters, searching for a pattern and building a new String.
A focused answer to AP CSA Topic 4.3, covering String traversal with a for loop, extracting one character with substring, the standard counting, searching and accumulation patterns, the half-open index range, and bounds safety, with a fully worked example.
Reviewed by: AI editorial process; not yet individually human-reviewed
Have a quick question? Jump to the Q&A page
Jump to a section
What this topic is asking
The College Board (Topic 4.3) wants you to develop algorithms that traverse a String using a loop together with the String methods from Unit 2 (length, substring, indexOf). The standard tasks are counting characters that satisfy a test, searching for a character or pattern, and building a new String by accumulation. The recurring technique is looping over every index and extracting one character at a time with substring(i, i + 1).
Traversing a String
The canonical loop visits every index:
for (int i = 0; i < s.length(); i++) {
String ch = s.substring(i, i + 1); // the character at index i, as a String
// process ch
}
The counting pattern
Initialise a counter to 0, and increment it whenever the current character meets a condition:
int vowels = 0;
for (int i = 0; i < s.length(); i++) {
String ch = s.substring(i, i + 1);
if (ch.equals("a") || ch.equals("e") || ch.equals("i")
|| ch.equals("o") || ch.equals("u")) {
vowels++;
}
}
The searching pattern
To find a character or pattern, you can either loop and test each position, or use indexOf. s.indexOf("x") returns the first index of "x", or -1 if absent. To find all occurrences, loop and advance past each match, or scan index by index.
The accumulation pattern
Accumulation is how you copy, filter, or reverse a String. Reversing prepends each character; filtering appends only the characters that pass a test.
Try this
Q1. Write the expression that extracts the character at index i of String s as a one-character String. [1 point]
- Cue.
s.substring(i, i + 1).
Q2. Explain why the loop bound should be i < s.length() rather than i <= s.length() when using substring(i, i + 1). [2 points]
- Cue. Valid indices run from 0 to
length() - 1; ati = length(),substring(i, i + 1)would read past the end and throw a StringIndexOutOfBoundsException.
Exam-style practice questions
Practice questions written in the style of College Board exam questions on this dot point, with worked answer explainers. The year tag is the paper they imitate, not the source.
AP 2022 (style)1 marksMultiple choice. Consider the following code segment.
```java
String s = "banana";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, i + 1).equals("a")) {
count++;
}
}
System.out.println(count);
```
What is printed?
(A) `3`
(B) `2`
(C) `6`
(D) `1`
(E) Nothing; a StringIndexOutOfBoundsException occurs.
Show worked answer →
The answer is (A).
The loop visits each index from 0 to s.length() - 1 (0 through 5). s.substring(i, i + 1) is the single character at index i. The characters of "banana" are b, a, n, a, n, a, so "a" matches at indices 1, 3 and 5: count ends at 3. The condition i < s.length() keeps i + 1 within bounds, so (E) does not occur. (B) misses one match; (C) counts every character.
Markers reward the standard single-character extraction substring(i, i + 1) and the bound i < length().
AP 2020 (style)4 marksFree response (code writing). A String `word` is given. Write a code segment that builds and prints the reverse of `word`. For example, if `word` is "cat", the output is "tac". Use a loop and substring; do not use any reverse library method.
Show worked answer →
A 4-point question testing String traversal and accumulation.
String reversed = "";
for (int i = 0; i < word.length(); i++) {
reversed = word.substring(i, i + 1) + reversed;
}
System.out.println(reversed);
Point 1: initialise an empty accumulator String reversed. Point 2: loop over every index with i < word.length(). Point 3: extract the character at i with substring(i, i + 1). Point 4: prepend it (char + reversed) so the characters end up reversed, then print. Appending instead of prepending would copy the word unchanged; iterating to i <= length() would throw an exception.
Related dot points
- Topic 4.2 for Loops: use a for loop, whose header combines initialisation, a boolean condition and an update, to repeat a block a controlled number of times, and convert between for and while loops.
A focused answer to AP CSA Topic 4.2, covering for-loop header syntax (init; condition; update), the order in which the three parts run, counting iterations, equivalence with while loops, common patterns, and tracing, with a fully worked example.
- Topic 4.1 while Loops: use a while loop to repeat a block of statements while a boolean condition remains true, with correct initialisation, condition and update to avoid infinite or off-by-one loops.
A focused answer to AP CSA Topic 4.1, covering while loop syntax, the initialise/test/update pattern, why each loop control variable must change, infinite loops and off-by-one errors, and how to trace iterations, with a fully worked example.
- Topic 4.4 Nested Iteration: write and trace nested loops, where an inner loop runs in full on each pass of an outer loop, and count the total number of inner-loop iterations.
A focused answer to AP CSA Topic 4.4, covering nested loops, how the inner loop completes fully on each outer pass, counting total iterations (including triangular patterns where the inner bound depends on the outer variable), and tracing nested output, with a fully worked example.
- Topic 2.7 String Methods: call the String methods in the AP Java subset (length, substring, indexOf, equals, compareTo), respecting zero-based indexing and the immutability of String objects.
A focused answer to AP CSA Topic 2.7, covering the required String methods length, substring (both forms), indexOf, equals and compareTo, zero-based indexing, the half-open range of substring, why == differs from equals, and String immutability, with a worked trace.
- Topic 4.5 Informal Code Analysis: determine the number of times a statement executes in a loop or nested loop by counting iterations, without using formal big-O notation.
A focused answer to AP CSA Topic 4.5, covering how to count statement executions in single and nested loops, the effect of step size and start/end bounds, conditional statements inside loops, and triangular versus rectangular counts, with a fully worked counting example.
Sources & how we know this
- AP Computer Science A Course and Exam Description — College Board (2025)