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
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 |
Return Type
String.indexOf() returns value of type int
.
✐ Examples
1 Find the index of "world" in the string
In this example,
- We create a string
str
with the value 'Hello, world!'. - We then use the
indexOf()
method to find the index of 'world'. - 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,
- We create a string
str
with the value 'ABCDEF'. - We then use the
indexOf()
method to find the index of 'D'. - 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,
- We create a string
str
with the value 'Lorem ipsum dolor sit amet'. - We then use the
indexOf()
method to find the index of 'ipsum'. - 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.