N Kaushik

How to check if a string contains another string in Dart

October 03, 2021

How to check if a string contains another string in Dart:

In this post, I will show you how to check if a string contains another string or not. Dart string provides one method called contains which can be used to do that.

Definition of contains:

contains is defined as like below:

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

The first one is a Pattern to check in the string and the second one is an optional value, the index to start the searching.

If we don’t provide startIndex, it will take 0 by default.

It returns one boolean value. true if the string or pattern is found, else false.

Example of contains:

Let’s take an example:

void main() {
  var givenStr = "Hello World";

It will print true because World is in the string givenString.

Example with regular expression:

We can also pass a regular expression:

void main() {
  var givenStr = "1234";

It will print false, because we are trying to find A to Z in the string givenStr which includes only numbers.

Example with starting index:

We can also pass the second argument, i.e. the starting index. For example,

void main() {
  var givenStr = "ABCD1234";
  print(givenStr.contains(RegExp(r'[A-Z]'), 4));

The starting index is 4, i.e. it will start the search from the fourth index. The string is ABCD1234. If we start from the fourth index, it will not find any character which is in A to Z. So, this example will print false.

Subscribe to my Newsletter

© 2021, nkaushik