OneBite.Dev - Coding blog in a bite size

Loop Through Each Character In A String In Dart

Code snippet for how to Loop Through Each Character In A String In Dart with sample and detail explanation

Dart language, one of the most versatile programming languages, allows developers to perform a variety of tasks efficiently. One of these tasks is looping through each character in a string which is quite common when developing software.

Code snippet for Looping Through Each Character In A String

void main() { 
   String str = "Hello, World!"; 
   for (var i = 0; i < str.length; i++) { 
      print(str[i]); 
   } 
}

Code Explanation for Looping Through Each Character In A String

The given snippet of code is written in Dart and is quite simple to understand, even for beginners. Let’s break it down step-by-step.

Firstly, we declare a main function void main() which is the entry point of the Dart program.

Within this function, we declare a String variable called str and assign the string “Hello, World!” to it.

Next, we start a for loop where we initialize an integer i to zero. The loop continues until i is less than the length of the string (str.length), incrementing i by 1 after each loop.

In every iteration of the loop, we print the i-th character of the string with print(str[i]);. So in the first iteration, it prints the first character of the string, in the second iteration it prints the second character, and so on.

When i is equal to the length of the string, the condition in the for loop (i < str.length) becomes false and the loop ends.

This way, the given Dart code loops through each character in a string and prints it. If you run the code with the string “Hello, World!”, it prints each character of the string on a new line. This code can be quite handy when you want to perform some operation on each character of a string in Dart.

dart