OneBite.Dev - Coding blog in a bite size

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

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

In software development, we often need to find the index of the first occurrence of a character in a string. For Dart developers, this process is streamlined and quite intuitive. In this article, we’ll explain how to achieve this using Dart, with an easy-to-understand code snippet and a detailed step-by-step explanation.

Code snippet for Finding The First Occurrence Of A Character In A String In Dart

Here’s an easy-to-run code snippet that can accurately target and identify the location of a character in a Dart string:

void main() {
  String str = "hello world!";
  String ch = "l";
  int index = str.indexOf(ch);
  print(index);
}

When you run this code snippet, the Dart compiler will return the index number of the first occurrence of the provided character in the string.

Code Explanation for Finding The First Occurrence Of A Character In A String In Dart

Let’s break down this code and explain each step:

  1. Firstly, we establish and declare the string we are working with. In this case, our string is “hello world!“.
String str = "hello world!";
  1. Secondly, we declare the letter we are searching for within our string. Here, we are looking for the letter “l”.
String ch = "l";
  1. We then use the Dart indexOf method on our established string — this method will return the index of the first occurrence of the provided character. If the character is not present in the string, it will return -1.
int index = str.indexOf(ch);
  1. Finally, we print the index onto the console:
print(index);

For our defined string and character, the printed result will be 2, as “l” is the 3rd character (indexes start from 0 in programming) in the string “hello world!“.

That’s how you can easily find the first occurrence of a character in a string in Dart. Keep in mind that this method also works for identifying the first occurrence of a substring in a string, not just single characters.

dart