Dart is one of the new and emerging programming languages developed by Google. It is specially designed for application development and used in Flutter. In Dart, we have many data types; one of them is a string. The string is an array of characters, such as names.
We can check whether or not the string starts with a specific pattern or a word. It is usually used with regex to get a string that begins with a particular pattern or word from the user's input.
The string.startsWith()
method helps achieve this task. It returns true if the first word in the string matches the pattern; otherwise, it returns false. This method is case sensitive, meaning ‘string’ and ‘String’ are two different words for this method.
The syntax of the string.startsWith()
method is the following:
string.startsWith(pattern, [index])
pattern
: This is a substring that is used to compare the parent string.
index
: This is an optional parameter that allows if substring starts at the index to match with the pattern or not.
import 'dart:convert';void main() {var str = 'Welcome to Educative Answers';print(str.startsWith('welcome'));print(str.startsWith('Welcome to'));}
Line 4: We store the main string in a variable named str
.
Line 6: We use the string.startsWith()
method to check if str
starts with 'welcome'. We print the resulting console.
Line 7: We use the string.startsWith()
method to check if str
starts with 'Welcome to'. We then print the result on the console.
Free Resources