Check if Two Strings are Equal
To check if given two strings are equal in Dart programming, we can use String.compareTo() method or Equal-to comparison operator.
Method 1 – Using String.compareTo()
Call compareTo()
method on the first string object, and pass the second string as argument to it. compareTo()
returns 0
if the two strings are equal.
Syntax
The syntax of the expression to check if string str1
is equal to the string str2
using compareTo()
method is
str1.compareTo(str2) == 0
The above expression returns true if str1
is equal to str2
, or false if not.
Example
In the following Dart program, we take two strings: str1
, and str2
; and check if these two strings are equal using String.compareTo()
method.
main.dart
void main() {
var str1 = 'apple';
var str2 = 'apple';
if ( str1.compareTo(str2) == 0 ) {
print('The two strings are equal.');
} else {
print('The two strings are not equal.');
}
}
Output
The two strings are equal.
Method 2 – Using Equal-to Operator
Equal-to operator can take the two strings as operands, and returns true if the strings are equal, or false if not.
Syntax
The syntax of the expression to check if string str1
is equal to the string str2
using equal-to operator is
str1 == str2
The above expression returns true if str1
is equal to str2
, or false if not.
Example
In the following Dart program, we take two strings: str1
, and str2
; and check if these two strings are equal using equal-to operator.
main.dart
void main() {
var str1 = 'apple';
var str2 = 'apple';
if ( str1 == str2 ) {
print('The two strings are equal.');
} else {
print('The two strings are not equal.');
}
}
Output
The two strings are equal.
Conclusion
In this Dart Tutorial, we learned how to check if two strings are equal, with examples.