OneBite.Dev - Coding blog in a bite size

Find The Last Occurrence Of A Character In A String In Dart

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

Dart is a powerful object-oriented programming language with strong backing by Google. One common operation while dealing with strings in this language is finding the last occurrence of a specific character in a string, and we will be learning how to achieve that in this article.

Code Snippet: Find The Last Occurrence Of A Character In A String In Dart

void main() { 
   String str = "Hello, World! World says hi again!"; 
   String searchChar = "l"; 
   int lastIndex = str.lastIndexOf(searchChar); 
   
   print("Last index of '$searchChar' is : $lastIndex"); 
}

Code Explanation: Find The Last Occurrence Of A Character In A String In Dart

In the above code snippet, we primarily used the lastIndexOf() method to find the last occurrence of a specific character in the string. Now, let’s break down our code snippet step by step to understand its execution:

  1. We started with the void main() function, the primary function executed in a Dart program.

  2. We then declared a String str, which contains the phrase “Hello, World! World says hi again!” This is the string where we will be searching for the character.

  3. We have another variable String searchChar assigned the value “l”. This is the character whose last occurrence we are aiming to find in our string.

  4. The int lastIndex = str.lastIndexOf(searchChar); is the function that does the primary action of finding the last occurrence of our character in the string. The lastIndexOf() function finds the position of the last occurrence of the specified character in the string. If the character is not found, the function will return -1.

  5. Finally, we print out the result using the print() function. This function prints to the console the message “The last index of ‘l’ is: ” followed by the index of the character’s last occurrence within the string.

Executing this script will display the last index of the character ‘l’ that is found in the string “Hello, World! World says hi again!” on the console output.

dart