Dart String Comparator
Solution 1:
Yes, ==
is the way to test if two Strings are equal (contain exclusively the same sequence of characters). The last line of your code evaluates to true
.
Solution 2:
Strings are immutable objects, which means you can create them but you can't change them. You can of course build a new string out of other strings, but once created, the string's contents are fixed.
This is an optimization, as two strings with the same characters in the same order can be the same object.
String rubi = 'good';
String ore = 'good';
print(rubi == ore); // true, contain the same characters
print(identical(rubi, ore)); // true, are the same object in memory
Solution 3:
Unlike Java, Dart allows to override operators such as ==
. So you can define your own test for this operator to check equality. You can also use indentical function to check whether two references are to the same object (the equivalent of ==
on objects in Java).
For Strings, it's a little special. Depending on how you instanciate the String you can have different results with DartVM :
main() {
final s = "test";
printTests(s, "test");
// displays '==' => true 'identical' => true
printTests(s, "$s");
// displays '==' => true 'identical' => false
printTests(s, new String.fromCharCodes(s.codeUnits));
// displays '==' => true 'identical' => false
}
printTests(String s1, String s2) {
print("'==' => ${s1 == s2} 'identical' => ${identical(s1, s2)}");
}
As you can see identical
returns true
only for the first case and ==
always true
. But that's not always true. If you run this code in javascript after a dart2js compilation, identical
and ==
always return true
.
In most case you want to compare the values of String not their references, so you should use ==
.
Solution 4:
(For completeness sake, here is another way to compare two strings.)
String
in Dart implements the Comparable
interface. You can use compareTo
to compare strings.
String rubi = 'good';
String ore = 'good';
rubi.compareTo(ore) == 0;
You need to check for NULL values though.