Dart – Find Index of other String in this String

To find the index of an other string in this string in Dart, call indexOf() method on this string and pass the other string as argument.

indexOf() method returns returns the index of first occurrence of the other string in this string.

We can also pass an optional starting position, as second argument, from which the search has to happen.

Syntax

The syntax to call indexOf() method on this string object str and pass the search string searchString as argument, and an optional starting position start is

str.indexOf(searchString, start)

If the search string is not present in this string, then indexOf() method returns an integer value of -1.

ADVERTISEMENT

Example

In this example, we take two strings: str and searchString, and find the index of first occurrence of the search string in this string, using indexOf() method.

main.dart

void main() {
  var str = 'Hello World';
  var searchString = 'or';
  var index = str.indexOf(searchString);
  print('Index = $index');
}

Output

Index = 7

Find Index of Search String after Specific Start Position

In this example, we take two strings: str and searchString, and find the index of first occurrence of the search string in this string, with start index of 5.

main.dart

void main() {
  var str = 'Hello World Hello User';
  var searchString = 'lo';
  var index = str.indexOf(searchString, 5);
  print('Index = $index');
}

Output

Index = 15

Conclusion

In this Dart Tutorial, we learned how to find the index of a search string in this string, using indexOf() method of String class, with examples.