Learn

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!.

Instructions

1.

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!

2.

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).

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?