Dart String startsWith()
Syntax & Examples
Syntax of String.startsWith()
The syntax of String.startsWith() method is:
bool startsWith(Pattern pattern, [int index = 0])
This startsWith() method of String checks whether this string starts with a match of pattern
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
pattern | required | the pattern to search for within the string |
index | optional [default value is 0] | if provided, matching will start at this index |
Return Type
String.startsWith() returns value of type bool
.
✐ Examples
1 Check if string starts with 'Hello'
In this example,
- We create a string
str
with the value 'Hello, world!'. - We then use the
startsWith()
method to check if it starts with 'Hello'. - Since the given string starts with 'Hello', the
startsWith()
method returnstrue
. - We print the result to standard output.
Dart Program
void main() {
String str = 'Hello, world!';
bool startsWithHello = str.startsWith('Hello');
print('Starts with \'Hello\' in str: $startsWithHello');
}
Output
Starts with 'Hello' in str: true
2 Check if string starts with 'A'
In this example,
- We create a string
str
with the value 'ABCDEF'. - We then use the
startsWith()
method to check if it starts with 'A'. - Since the given string starts with 'A', the
startsWith()
method returnstrue
. - We print the result to standard output.
Dart Program
void main() {
String str = 'ABCDEF';
bool startsWithA = str.startsWith('A');
print('Starts with \'A\' in str: $startsWithA');
}
Output
Starts with 'A' in str: true
3 Check if string starts with 'Lorem'
In this example,
- We create a string
str
with the value 'Lorem ipsum dolor sit amet'. - We then use the
startsWith()
method to check if it starts with 'Lorem'. - Since the given string starts with 'Lorem', the
startsWith()
method returnstrue
. - We print the result to standard output.
Dart Program
void main() {
String str = 'Lorem ipsum dolor sit amet';
bool startsWithLorem = str.startsWith('Lorem');
print('Starts with \'Lorem\' in str: $startsWithLorem');
}
Output
Starts with 'Lorem' in str: true
Summary
In this Dart tutorial, we learned about startsWith() method of String: the syntax and few working examples with output and detailed explanation for each example.