OneBite.Dev - Coding blog in a bite size

Find The Position Of The First Occurrence Of A Substring In A String In Dart

Code snippet for how to Find The Position Of The First Occurrence Of A Substring In A String In Dart with sample and detail explanation

In this article, we will understand how to find the position of the first occurrence of a substring in a string in Dart. This can be particularly useful when working with large strings and helps in efficiently manipulating and accessing data.

Code Snippet

Here’s a simple example showing how you can find the first occurrence of a substring in a Dart string:

void main() {
  String str = 'I love programming in dart. It is my favorite language';
  String subStr = 'dart';
  
  int position = str.indexOf(subStr);
  
  print('The first occurrence of the substring is at: $position');
}

This program prints:

The first occurrence of the substring is at: 25

Code Explanation

The indexOf() function is a built-in Dart function that can be used to find the first index of a substring in a given string. It finds the position by checking each character in the target string against the substring.

Let’s break it down :

  • Firstly, we define our main string as ‘I love programming in dart. It is my favorite language’ and the substring as ‘dart’.

  • Then, we make use of the indexOf() function to find the first occurrence of the “dart” in the string.

  • int position = str.indexOf(subStr); : This line of code tries to find the index of the first occurrence of the substring “dart” in the string str.

  • If the substring exists within the string, indexOf() returns the index of the first character of the first occurrence of the substring. If the substring doesn’t exist, it returns -1.

  • The index is 0-based, meaning the first character in the string is at index 0, the second character is at index 1, and so on.

  • Finally, we print out the value of position.

Remember also that Dart is case sensitive. So, for instance, searching for ‘Dart’ (with a capital ‘D’) in the string would return -1, as it does not exactly match ‘dart’.

This is a simple and effective way to get the position of the first occurrence of a substring within a string in Dart.

dart