OneBite.Dev - Coding blog in a bite size

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

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

When programming in Dart, there may be instances where you need to find the position of the last occurrence of a substring in a string. This article will guide you through the process of writing a simple piece of code to achieve this goal in Dart.

Code snippet for finding the last occurrence of a substring in a string

void main() {
  String str = 'Hello, World From The Dart Programming Language';
  String substr = 'The';
  
  int position = str.lastIndexOf(substr);
  
  print('The last occurrence of "${substr}" is at index: ${position}');
}

Code Explanation for finding the last occurrence of a substring in a string

This simple Dart code snippet is used to find the position of the last occurrence of a specific substring within a string.

To start, we declare a main function, which is the entry point of a Dart program:

void main() {
  // code goes here
}

Next, we create a string for our program to search through:

String str = 'Hello, World From The Dart Programming Language';

In this case, our string is ‘Hello, World From The Dart Programming Language’.

Then, we define a substring we want to find the last occurrence of:

String substr = 'The';

Here, our substring is “The”.

After defining our string and substring, we want to find the last position of our substring within the string. To do this, we use Dart’s built-in lastIndexOf method with our substring as the input:

int position = str.lastIndexOf(substr);

This piece of code scans through the defined string from the end to the beginning, and returns the index of the last occurrence of the substring. If the substring isn’t found, it’ll return -1.

Finally, we print out the position:

print('The last occurrence of "${substr}" is at index: ${position}');

Here, it interpolates the substring and the position we just found into a string and prints it out. The program will output ‘The last occurrence of “The” is at index: 21’.

In this tutorial, you learned how to find the last occurrence of a substring in a Dart string. This is a simple, but useful, trick to have in your Dart programming toolkit.

dart