Skip to main content
United StatesComputer ScienceSyllabus dot point

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.

Generated by Claude Opus 4.811 min answer

Reviewed by: AI editorial process; not yet individually human-reviewed

Have a quick question? Jump to the Q&A page

Jump to a section
  1. What this topic is asking
  2. Traversing a String
  3. The counting pattern
  4. The searching pattern
  5. The accumulation pattern
  6. Try this

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; at i = 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

Sources & how we know this