Iterating Through Strings

Aside from sequences of numbers, we can also loop over Strings! After all, a string is a collection of characters.

Let’s say we wanted to look over a string and see if it contains "z". In a program, that means we would loop through the characters of a String. In each iteration would we check if the character was a "z".

var quote = "our whole life is solving puzzles." for character in quote { print(character) if character == "z" { print("There's a z!") } }

The basic structure of the for-in loop remains the same, but now we’re going through each character of our String, instead of each number of a range.

The example above would print out:

o u r w h ... z There's a z! z There's a z! l e s .

In our print out, we see that each character of the String is printed out (we skipped over a few characters with a ... to lessen the amount printed). Additionally, each time character is a "z" we also print out There's a z!.



Create a for-in loop that iterates over the characters in funFact using char as the iterator (placeholder) variable.

Note: you will see a warning after passing this step, but it’ll go away in the next step!


Inside the body of the loop:

  • Add an if statement that checks if the character (char) is not an "x".
  • Inside the if statement, use print() to print out the character (char).
Folder Icon

Take this course for free

Already have an account?