OneBite.Dev - Coding blog in a bite size

Convert A String To An Array In Dart

Code snippet for how to Convert A String To An Array In Dart with sample and detail explanation

String manipulation is a common task in programming. In this article, we will discuss how to convert a string to an array in Dart, a programming language commonly used in Flutter development.

Code snippet to Convert a String to an Array

Here is a simple method in Dart to convert a string to an array:

void main() {
    String str = "Hello World";
    List<String> strArray = str.split('');
    print(strArray);
}

In this code snippet, we are first initializing a simple string “Hello World”. Then using the split('') method, we are converting the string into an array and printing it onto the console.

Code Explanation for Converting a String to an Array in Dart

In the given code snippet, we are creating a Dart application to convert a string to an array.

  1. String str = "Hello World";: Here, we are defining and initializing a string named ‘str’.

  2. List<String> strArray = str.split('');: The ‘split()’ function is a built-in function in Dart which is used to split a string into substrings based on the pattern specified. In this case, we are passing an empty pattern (”), thereby getting each individual character in the string as an element in the array.

  3. print(strArray);: This line of code prints the resultant array on the console. Each character of the string will be a separate element in the array.

So, if the string is “Hello World”, the output of the program will be [ ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ’ ’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’ ].

Hence, using the split method, you can easily convert a string into an array in Dart. This method can be very handy when you want to perform operations on individual characters of a string.

dart