Course contentsShow
← Computer Science
Lesson 263 of 2,8726. Arrays and Basic CollectionsFree lesson

String Traversal with Loops

Iterating through each character in a string using for loops, while loops, and enhanced for-each constructs.

String Traversal with Loops

What you'll learn: How to visit each character in a string one by one using different looping techniques.

The Core Idea

Since strings are arrays of characters (as you learned in lesson 260), you can walk through them character by character using the same loop patterns you already know. String traversal means systematically accessing each character in sequence, from start to finish, to examine, count, or process them.

Think of a string as a row of books on a shelf. Traversal is like running your finger along the spine of each book, one by one, reading each title.

Using a While Loop

You can traverse a string with a while loop by tracking your position with an index variable:

i = 0
text = "hello"
while i < length of text:
    character = text[i]
    // do something with character
    i = i + 1

Using a For Loop

A for loop is more compact for traversal since it handles initialization, condition, and update automatically:

text = "world"
for i from 0 to length of text - 1:
    character = text[i]
    // process character

Using Enhanced For-Each

Many languages offer a for-each construct that automatically visits each character without needing an index:

text = "coding"
for each character in text:
    // work with character directly

This is cleanest when you don't need to know the position—just the character itself.

Key Takeaway: String traversal uses standard loops (while, for, for-each) to visit each character sequentially; choose the loop type based on whether you need index access or just the characters themselves.