Now that you’ve seen for-loops in action, it’s time to put your new found knowledge to the test. And for this, I want you to create a variable to hold the sentence, ‘Dart is cool’. Well, you can pick any sentence you want. The text isn’t so much the point.
Once you have your sentence in your variable, I want you to loop through it. Yes - that’s right - you can use a for-loop to loop through each character of any string. You can think of it as a collection of characters. To access the first character on a string, you access it like a list.
How’d that challenge work for you? Hopefully, it wasn’t too difficult. Follow along with me. Start by creating a new session in DartPad.dev. First, we’ll create our sentence.
const sentence = 'dart is cool';
Now, we’ll write our for-loop. We start with the for keyword.
for()
Next, we setup our iterator.
for(var i=0;)
Then we provide a condition. In this case, the sentence is composed of twelve characters so we want to loop through less than twelve. Remember, the first element is zero.
for(var i=0;i <12)
Now we could use that, but the string has property that automatically gives us the character count. This is the length property. You’ll learn all about properties in a later course.
for(var i=0;i < sentence.dart)
Notice we are checking to see if the iterator is less than length versus less than or equal. Remember, lists are zero based. While a string isn’t a list, it follows the same rules. The first character is located at the zero index. The last character is found at the 11th index. The length lets us know how characters are in the string which is twelve. Thus, we look less than the length;
Great, now lets increment the iterator.
for(var i=0;i < sentence.length; i++)
Finally, we’ll print out each character.
for(var i=0;i < sentence.length; i++) {
print(sentence[i])
}
And that’s it. Run your program, and you’ll see each character printed to the console. Well done.