Unit 2 Cycle 2 Day 10: Complex String Traversal Algorithm
Share
Complex String Traversal Algorithm
Section 2.11 — String Traversal
Key Concept
Complex string traversal algorithms combine character-by-character processing with conditional logic and accumulation. A common pattern counts specific character types, builds a transformed string, or searches for patterns. The AP exam tests multi-step string algorithms where you must track both the loop index and an accumulator (count, result string, or boolean flag) through each iteration. Careful attention to whether the loop uses charAt() returning a char or substring() returning a String is essential for comparison operations.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) ABCD
a(0) A(1) b(2) B(3) c(4) C(5) d(6) D(7). Loop: i=0: substring(1,2)="A". i=2: substring(3,4)="B". i=4: substring(5,6)="C". i=6: substring(7,8)="D". Result: "ABCD".
Why Not the Others?
(B) The code takes index i+1 (the second of each pair), which is the uppercase letter.
(C) The loop steps by 2 and takes only one character per step, not both.
(D) The original string is not returned; only every other character starting from index 1.
Common Mistake
With i += 2, the loop visits indices 0, 2, 4, 6. But the substring uses i + 1, so it extracts indices 1, 3, 5, 7. This selects every second character starting from the second one.
AP Exam Tip
When a loop index and the substring index differ (i vs i+1), trace the actual indices being extracted, not the loop variable values.