Dart String lastIndexOf()
Syntax & Examples


Syntax of String.lastIndexOf()

The syntax of String.lastIndexOf() method is:

 int lastIndexOf(Pattern pattern, [int? start]) 

This lastIndexOf() method of String returns the starting position of the last match pattern in this string.

Parameters

ParameterOptional/RequiredDescription
patternrequiredthe pattern to search for within the string
startoptional [default value is 0]if provided, search starts at this index

Return Type

String.lastIndexOf() returns value of type int.



✐ Examples

1 Find last occurrence of 'world!'

In this example,

  1. We create a string str with the value 'Hello, world! User world!'.
  2. We then use the lastIndexOf() method to find the last occurrence of 'world!'. Since the given string contains 'world!' as its last occurrence, the method returns the index of 'w', which is 7.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Hello, world! User world!';
  int lastIndex = str.lastIndexOf('world');
  print('Last index of "world" in str: $lastIndex');
}

Output

Last index of "world" in str: 19

2 Find last occurrence of 'D'

In this example,

  1. We create a string str with the value 'ABCDEFDFN'.
  2. We then use the lastIndexOf() method to find the last occurrence of 'D'. Since the given string contains 'D' at index 3, the method returns 3.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'ABCDEFDFN';
  int lastIndex = str.lastIndexOf('D');
  print('Last index of "D" in str: $lastIndex');
}

Output

Last index of "D" in str: 6

3 Find last occurrence of 'ipsum'

In this example,

  1. We create a string str with the value 'Lorem ipsum dolor sit amet'.
  2. We then use the lastIndexOf() method to find the last occurrence of 'ipsum'. Since the given string contains 'ipsum' at index 6, the method returns 6.
  3. We print the result to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  int lastIndex = str.lastIndexOf('ipsum');
  print('Last index of "ipsum" in str: $lastIndex');
}

Output

Last index of "ipsum" in str: 6

Summary

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