OneBite.Dev - Coding blog in a bite size

Search For A Character In A String In Dart

Code snippet for how to Search For A Character In A String In Dart with sample and detail explanation

Searching for a particular character in a string is a common scenario when handling data in any programming language. In Dart, this task can be accomplished through various methods. In this article, we will focus on how to use the contains() method to find a character in a string.

Code snippet: Finding a Character in a String

To find if a character exists in a string, Dart provides the contains() method. Here is an example of how you can use it:

void main() {
  String str = 'Hello, World!';
  bool result = str.contains('o');
  
  print(result);
}

In this code snippet, the contains() method checks if the string str contains the character ‘o’. The result, which will either be true or false, is then printed to the console.

Code Explanation: Finding a Character in a String

This code can be broken down into three main parts:

  1. String Initialization: The first thing we do is initialize a String variable named str with the value 'Hello, World!'.
String str = 'Hello, World!';
  1. Using the contains() Method: Next, we use the contains() method to check if our string contains the character we’re looking for - in this case, ‘o’. Note that the contains() method is case-sensitive, so it will return false if we used ‘O’ as the parameter instead of ‘o’.
bool result = str.contains('o');
  1. Printing the Result: The contains() method returns a boolean value (true if the character is found, false otherwise) which we store in the result variable. Finally, we print out result to the console.
print(result);

If the character ‘o’ is present in the string, the code will output true; if not, it will return false. This simple but powerful Dart capability can be incredibly useful when dealing with string manipulation and data processing.

dart