String Traversals
Explore how to traverse and process strings in Java by implementing methods such as indexOf and replace using loops. This lesson helps you understand loop control, string manipulation, and algorithm design to handle string data effectively for the AP Computer Science exam.
We'll cover the following...
Back in Unit 2, we studied Java strings. We learned how to process strings and traverse through them using methods. In this section, we’ll cover a few examples of processing strings by writing our loops.
🧠 Note: Remember that strings are made of characters. Each index carries one character.
Implementing indexOf() from scratch
Brush up on our discussion about the indexOf() method (click here). It returns the index of the very first occurrence of a character. If a character isn’t found, it returns .
Let’s try to implement the indexOf() method via a loop. The question is, which loop do we choose: the while loop or the for loop? Well, the while loop makes sense because it is the input-controlled ...