Dart String substring()
Syntax & Examples


Syntax of String.substring()

The syntax of String.substring() method is:

 String substring(int start, [int? end]) 

This substring() method of String returns the substring of this string from start, inclusive, to end, exclusive.

Parameters

ParameterOptional/RequiredDescription
startrequiredthe starting index of the substring
endoptionalthe ending index of the substring (exclusive)

Return Type

String.substring() returns value of type String.



✐ Examples

1 Extract "world" from string

In this example,

  1. We create a string str1 with the value 'Hello, world!'.
  2. We use the substring() method with start index 7 and end index 12 to extract the substring 'world'.
  3. We print the extracted substring to standard output.

Dart Program

void main() {
  String str1 = 'Hello, world!';
  String sub1 = str1.substring(7, 12);
  print('Substring 1: $sub1');
}

Output

Substring 1: world

2 Extract substring from index 2 to end

In this example,

  1. We create a string str2 with the value 'ABCDEF'.
  2. We use the substring() method with start index 2 to extract the substring from index 2 to the end of the string.
  3. We print the extracted substring to standard output.

Dart Program

void main() {
  String str2 = 'ABCDEF';
  String sub2 = str2.substring(2);
  print('Substring 2: $sub2');
}

Output

Substring 2: CDEF

3 Extract 'ipsum' from string

In this example,

  1. We create a string str3 with the value 'Lorem ipsum dolor sit amet'.
  2. We use the substring() method with start index 6 and end index 11 to extract the substring 'ipsum'.
  3. We print the extracted substring to standard output.

Dart Program

void main() {
  String str3 = 'Lorem ipsum dolor sit amet';
  String sub3 = str3.substring(6, 11);
  print('Substring 3: $sub3');
}

Output

Substring 3: ipsum

Summary

In this Dart tutorial, we learned about substring() method of String: the syntax and few working examples with output and detailed explanation for each example.