Dart 字符串比较器

比较 Dart 中字符串的最好方法是什么?String 类不包含 equals方法。建议使用 ==吗?

例如:

String rubi = 'good';
String ore = 'good';


rubi == ore;
101256 次浏览

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.

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

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 ==.

(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.

There are several ways to compare String. Depending on your need, you should choose an appropriate solution:

  1. Using operator str1 == str2: The operator returns true if the str1 equals str2. Otherwise, it returns false. This operator is useful when you want to determine whether the strings have the same sequence of code units.
  2. Using str1.compareTo(str2) method: the method returns a negative value (-1) if str1 is ordered before str2, a positive value (1) if str1 is ordered after str2, or zero if str1 and str2 are equivalent. This method is useful if you want to sort a collection of strings.