Dart String contains()
Syntax & Examples

Syntax of String.contains()

The syntax of String.contains() method is:

 bool contains(Pattern other, [int startIndex = 0]) 

This contains() method of String checks whether this string contains a match of other.

Parameters

ParameterOptional/RequiredDescription
otherrequiredthe pattern to search for within the string
startIndexoptional [default value is 0]if provided, matching will start at this index

Return Type

String.contains() returns value of type bool.



✐ Examples

1 Check if "world" is in the string

In this example,

  1. We create a string str with the value 'Hello, world!'.
  2. We then use the contains() method to check if "world" is present in the string.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Hello, world!';
  bool containsWorld = str.contains('world');
  print('Contains "world" in str: $containsWorld');
}

Output

Contains "world" in str: true

2 Check if 'D' is in the string

In this example,

  1. We create a string str with the value 'ABCDEF'.
  2. We then use the contains() method to check if 'D' is present in the string.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  bool containsD = str.contains('D');
  print('Contains "D" in str: $containsD');
}

Output

Contains "D" in str: true

3 Check if 'ipsum' is in the string

In this example,

  1. We create a string str with the value 'Lorem ipsum dolor sit amet'.
  2. We then use the contains() method to check if 'ipsum' is present in the string.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  bool containsIpsum = str.contains('ipsum');
  print('Contains "ipsum" in str: $containsIpsum');
}

Output

Contains "ipsum" in str: true

Summary

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