String Traversals

Learn how to implement the String functions using loops.

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 −1-1.

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 loop. It depends on the input given by the user. Additionally, we are not sure how many times the loop will run. So, using a while loop is the best choice.

Let’s try to implement it.

Get hands-on with 1200+ tech skills courses.