Unit 2 Cycle 2 Day 21: String Processing with Conditional Replace
Share
String Processing with Conditional Replace
Section 2.11 — String Traversal
Key Concept
String processing with conditional replacement builds a new string by iterating through the original and replacing certain characters or substrings. The pattern is: for (int i = 0; i < str.length(); i++) { if (condition) result += replacement; else result += str.substring(i, i+1); }. The AP exam tests variations where the replacement is a different character, the condition involves checking neighboring characters, or the replacement is a different length than the original, which changes the indices if you are not building a new string.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) Java_is_fun
The code replaces every space with an underscore. J-a-v-a: kept. Space: replaced with _. i-s: kept. Space: replaced with _. f-u-n: kept. Result: "Java_is_fun".
Why Not the Others?
(B) The original string has spaces, but the code replaces them with underscores.
(C) Both spaces are replaced, not just the first one.
(D) Both spaces are replaced. The loop processes every character.
Common Mistake
String traversal with character replacement builds a new string character by character. Since Strings are immutable in Java, you must build a new String (you cannot modify the original).
AP Exam Tip
String replacement via traversal is a common AP exam pattern. Build a new string, checking each character and appending the original or replacement.