Unit 2 Cycle 1 Day 24: While Loop with String Processing

Unit 2 Foundation (Cycle 1) Day 24 of 28 Foundation

While Loop with String Processing

Section Mixed — Review: Loops and Strings

Key Concept

While loops processing strings character by character use an index variable that advances through the string. The condition typically checks index < str.length() and may also include a content-based condition (like searching for a specific character). A common pattern is a search loop that terminates either when the target is found or the end of the string is reached. The AP exam tests whether you correctly handle both termination cases and what the final value of the index reveals about the search result.

Consider the following code segment.

String s = "abcabc"; int idx = s.indexOf("c"); int count = 0; while (idx != -1) { count++; idx = s.indexOf("c", idx + 1); } System.out.println(count);

What is printed as a result of executing the code segment?

Answer: (B) 2

First indexOf("c") returns 2. count=1. Next indexOf("c", 3) returns 5. count=2. Next indexOf("c", 6) returns -1. Loop ends. count = 2.

Why Not the Others?

(A) There are two c's in "abcabc": at index 2 and index 5.

(C) There are exactly 2 c's, not 3.

(D) 6 is the length of the string, not the count of c's.

Common Mistake

The two-argument indexOf starts searching from the given index. After finding a match, start the next search at idx + 1 to skip past the found character.

AP Exam Tip

This is a standard character-counting pattern using indexOf in a while loop. The loop continues until indexOf returns -1 (not found).

Review this topic: Section Mixed — Review: Loops and Strings • Unit 2 Study Guide

More Practice

Related FRQs

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.