Reputation: 1135
What is the best way to compare Strings in Dart? The String class does not contain an equals
method. Is ==
recommended?
For example:
String rubi = 'good';
String ore = 'good';
rubi == ore;
Upvotes: 110
Views: 139514
Reputation: 602
There are several ways to compare String. Depending on your need, you should choose an appropriate solution:
Upvotes: 5
Reputation: 7106
(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.
Upvotes: 8
Reputation: 76333
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 ==
.
Upvotes: 15
Reputation: 3923
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
Upvotes: 28
Reputation: 34051
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
.
Upvotes: 164