OneBite.Dev - Coding blog in a bite size

Slice A String In Dart

Code snippet for how to Slice A String In Dart with sample and detail explanation

Manipulating strings is a fundamental aspect of programming, and Dart programming is no exception. The Dart language provides a variety of ways to slice or split up strings, and in this article, we will discuss the String Slice concept and how to implement it.

Code snippet for String Slice in Dart

Here is a simple example demonstrating how to slice a string in Dart:

void main() {
  String str = 'Hello, there!';

  var slice = str.substring(0, 5);

  print(slice);
}

When you run this program, it outputs:

Hello

Code Explanation for String Slice in Dart

In Dart, substring() method is used to slice a string. It extracts parts of a string and returns the extracted parts in a new string. In our code, we’re applying the substring() method to the str variable, which contains the string Hello, there!.

Let’s break down the code:

Step 1: Declare a String variable.

String str = 'Hello, there!';

We initialize a String str with the value 'Hello, there!'.

Step 2: Slice the string.

var slice = str.substring(0, 5);

Here, we’re using the substring() method to slice our string. The substring() method takes two arguments: the starting index and the end index. In this case, we started from index 0 and ended at index 5, so it sliced out the string from index 0 to 5 (excluding 5) which is 'Hello'.

Step 3: Print the sliced string.

print(slice);

Finally, the print() function is used to print out the value of slice, which displays 'Hello'.

So, using the substring() method in Dart, you can slice a portion of a string based on the indices you specify. Note that the original string remains unchanged.

dart