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:
Parameter | Optional/Required | Description |
---|---|---|
pattern | required | the pattern to search for within the string |
startIndex | optional [default value is 0] | if provided, matching will start at this index |
String.indexOf() returns value of type int
.
In this example,
str
with the value 'Hello, world!'.indexOf()
method to find the index of 'world'.void main() {
String str = 'Hello, world!';
int index1 = str.indexOf('world');
print('Index of "world" in str: $index1');
}
Index of "world" in str: 7
In this example,
str
with the value 'ABCDEF'.indexOf()
method to find the index of 'D'.void main() {
String str = 'ABCDEF';
int index2 = str.indexOf('D');
print('Index of "D" in str: $index2');
}
Index of "D" in str: 3
In this example,
str
with the value 'Lorem ipsum dolor sit amet'.indexOf()
method to find the index of 'ipsum'.void main() {
String str = 'Lorem ipsum dolor sit amet';
int index3 = str.indexOf('ipsum');
print('Index of "ipsum" in str: $index3');
}
Index of "ipsum" in str: 6
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.