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.
Parameter | Optional/Required | Description |
---|---|---|
pattern | required | the pattern to search for within the string |
start | optional [default value is 0] | if provided, search starts at this index |
String.lastIndexOf() returns value of type int
.
In this example,
str
with the value 'Hello, world! User world!'.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.void main() {
String str = 'Hello, world! User world!';
int lastIndex = str.lastIndexOf('world');
print('Last index of "world" in str: $lastIndex');
}
Last index of "world" in str: 19
In this example,
str
with the value 'ABCDEFDFN'.lastIndexOf()
method to find the last occurrence of 'D'. Since the given string contains 'D' at index 3, the method returns 3.void main() {
String str = 'ABCDEFDFN';
int lastIndex = str.lastIndexOf('D');
print('Last index of "D" in str: $lastIndex');
}
Last index of "D" in str: 6
In this example,
str
with the value 'Lorem ipsum dolor sit amet'.lastIndexOf()
method to find the last occurrence of 'ipsum'. Since the given string contains 'ipsum' at index 6, the method returns 6.void main() {
String str = 'Lorem ipsum dolor sit amet';
int lastIndex = str.lastIndexOf('ipsum');
print('Last index of "ipsum" in str: $lastIndex');
}
Last index of "ipsum" in str: 6
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.