Dart String compareTo()
Syntax & Examples
Syntax of String.compareTo()
The syntax of String.compareTo() method is:
int compareTo(String other)
This compareTo() method of String compares this string to other
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
other | required | the pattern to search for within the string |
Return Type
String.compareTo() returns value of type int
.
✐ Examples
1 Check if "world" is in the string
In this example,
- We create a string
str
with the value 'Hello, world!'. - We then use the
contains()
method to check if "world" is present in the string. - We print the result to standard output.
Dart Program
void main() {
String str = 'Hello, world!';
bool containsWorld = str.contains('world');
print('Contains "world" in str: $containsWorld');
}
Output
Contains "world" in str: true
2 Check if "D" is in the string
In this example,
- We create a string
str
with the value 'ABCDEF'. - We then use the
contains()
method to check if 'D' is present in the string. - We print the result to standard output.
Dart Program
void main() {
String str = 'ABCDEF';
bool containsD = str.contains('D');
print('Contains "D" in str: $containsD');
}
Output
Contains "D" in str: true
3 Check if "ipsum" is in the string
In this example,
- We create a string
str
with the value 'Lorem ipsum dolor sit amet'. - We then use the
contains()
method to check if 'ipsum' is present in the string. - We print the result to standard output.
Dart Program
void main() {
String str = 'Lorem ipsum dolor sit amet';
bool containsIpsum = str.contains('ipsum');
print('Contains "ipsum" in str: $containsIpsum');
}
Output
Contains "ipsum" in str: true
Summary
In this Dart tutorial, we learned about compareTo() method of String: the syntax and few working examples with output and detailed explanation for each example.