Unit 1 Cycle 2 Day 15: Complex String Manipulation
Share
Complex String Manipulation
Section 1.10 — Strings: Methods
Key Concept
Complex string manipulation problems chain multiple String methods together, requiring careful tracking of intermediate values. A pattern like s.substring(s.indexOf("a") + 1, s.lastIndexOf("a")) extracts text between the first and last occurrence of a character. The AP exam tests whether you can correctly evaluate each method call in sequence without losing track of index positions. Write down the string with index numbers above each character to avoid off-by-one errors when evaluating these chains.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) ACEG 4
The loop increments by 2, visiting every other index:
i=0: substring(0,1) = "A"
i=2: substring(2,3) = "C"
i=4: substring(4,5) = "E"
i=6: substring(6,7) = "G"
i=8: Loop ends (8 < 8 is false).
result: "ACEG" (4 characters).
Why Not the Others?
(B) This would require starting at index 1 (i = 1; i += 2). The loop starts at 0, selecting even-indexed characters.
(C) This would require incrementing by 1. The i += 2 skips every other character.
(D) The result is "ACEG" which has 4 characters, not 8. The length() call returns the length of result, not the original string.
Common Mistake
When a loop increments by 2, it visits half the indices. With i += 2 starting at 0, it visits indices 0, 2, 4, 6. Starting at 1 would give 1, 3, 5, 7 instead.
AP Exam Tip
For string traversal with non-standard increments, list out the values of i before tracing the body. This reveals the pattern: every other character, every third character, etc.