OneBite.Dev - Coding blog in a bite size

Find The Index Of A Substring Within A String In Dart

Code snippet for how to Find The Index Of A Substring Within A String In Dart with sample and detail explanation

Navigating through the world of coding presents a variety of scenario where you may need to search strings; finding the index of a substring within a string is inevitable. Dart, an open-source, general-purpose, class-based, object-oriented language with C-style and syntax, simplifies these tasks. Below is a code snippet on how to achieve this.

Code Snippet: Find The Index Of A Substring Within A String In Dart

void main() { 
   String str = "Hello from Askippy"; 
   String subStr1 = "from";

   print('Substring starts at Index: ${str.indexOf(subStr1)}');  
}

When you run this code, it outputs the index where the substring ‘from’ starts within the str string.

Code Explanation: Find The Index Of A Substring Within A String In Dart

Given the string “Hello from Askippy”, suppose we want to find where the substring “from” starts. Here’s how to go about it:

  1. Define String and Substring. The first step is to initialize or define your main string and the substring you want to search in the main string.
   String str = "Hello from Askippy"; 
   String subStr1 = "from";
  1. Use the indexOf() Method. Dart provides a method called indexOf() that you can use to obtain the index of the start of a substring in a given string.
   str.indexOf(subStr1);

This code returns the index of the first occurrence of the substring in the main string. If the substring is not in the main string, it returns -1.

  1. Print the Index. Display the index using the print statement. The snippet here uses string interpolation to embed the result into a larger string:
   print('Substring starts at Index: ${str.indexOf(subStr1)}'); 

When you run the entire code, it will print out “Substring starts at Index: 6”. This output means that the substring “from” starts at the 6th index of the string “Hello from Askippy”.

dart