Dart String indexOf()
Syntax & Examples

Syntax of String.indexOf()

The syntax of String.indexOf() method is:

 int indexOf(Pattern pattern, [int start = 0]) 

This indexOf() method of String returns the position of the first match of pattern in this string, starting at start, inclusive:

Parameters

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

Return Type

String.indexOf() returns value of type int.



✐ Examples

1 Find the index of "world" in the string

In this example,

  1. We create a string str with the value 'Hello, world!'.
  2. We then use the indexOf() method to find the index of 'world'.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Hello, world!';
  int index1 = str.indexOf('world');
  print('Index of "world" in str: $index1');
}

Output

Index of "world" in str: 7

2 Find the index of 'D' in the string

In this example,

  1. We create a string str with the value 'ABCDEF'.
  2. We then use the indexOf() method to find the index of 'D'.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  int index2 = str.indexOf('D');
  print('Index of "D" in str: $index2');
}

Output

Index of "D" in str: 3

3 Find the index of 'ipsum' 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 indexOf() method to find the index of 'ipsum'.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  int index3 = str.indexOf('ipsum');
  print('Index of "ipsum" in str: $index3');
}

Output

Index of "ipsum" in str: 6

Summary

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