AP® Computer Science A · Unit 2 · Topic 2.10

Traversing a String Character by Character

Traversing a string means visiting each character in turn with a loop whose counter runs from 0 to length() - 1, so you can inspect, count, or test characters one at a time.

Some problems about strings can't be answered by looking at the whole thing at once. Counting vowels, finding a space, checking if a string is a palindrome: each of these needs you to examine individual characters and build up an answer as you go. Traversal breaks a big string problem into a sequence of small, identical decisions, one per character.

The standard pattern uses a for loop with an index variable, usually i, starting at 0 and running while i is less than s.length(). On each pass, s.charAt(i) hands you the character sitting at position i. Since i takes every value from 0 up to length() - 1 exactly once, the loop visits every character exactly once, in order, with no repeats and no skips. The index variable isn't just a counter ticking along beside the string; it IS the position currently being examined, which is why a trace table showing i's value also shows you where the loop is looking.

This connects directly to the rest of the unit: the loop's condition (i < s.length()) is the same kind of boolean test you've been tracing in while and for loops, and finding a character often means pairing the loop with an if statement that checks s.charAt(i) against some target. Once a match is found, many traversals break out early or return, which is the same short-circuit instinct you use with boolean logic, just applied to stopping a loop instead of skipping a branch.

Key terms

traversal
Visiting every element of a structure, such as a string's characters, one at a time in order.
index
A whole number position in a string, starting at 0 for the first character and ending at length() - 1.
charAt(i)
A String method that returns the character sitting at position i.
StringIndexOutOfBoundsException
An error thrown when code tries to access a string index that doesn't exist, such as index length().

Watch it explained

  1. How it worksHow does a loop over indices 0 through length minus 1 visit every character exactly once?
  2. Worked exampleTrace a loop that counts the vowels in the word ALGORITHM.
  3. Worked exampleFind the index the loop sits at when it first meets a space in HELLO THERE.
  4. Common mistakeWhy doesn't charAt(s.length()) hand you the last character of a string?

Check yourself

Your turn1 of 2
A loop scans a string of length 24 looking for the first space, which happens to sit at index 6. At what index does the loop's counter sit when it first finds the space?

End of topic.