Dart – Compare Strings

To compare two strings in Dart, call compareTo() on the first string and pass the second string as argument. compareTo() returns

  • negative value if first string is less than the second string.
  • zero if first string equals second string.
  • positive value if first string is greater than the second string.

The string comparison happens lexicographically.

Syntax

The syntax to call compareTo() method of first string and pass the second string as argument is

firstString.compareTo(secondString)

where firstString and secondString are string values.

ADVERTISEMENT

Example

In this example, we take two strings and compare them using compareTo() method. We use if-else-if statement to check if the first string is less than, greater than, or equal to the second string.

main.dart

void main() {
  var str1 = 'apple';
  var str2 = 'banana';
  var result = str1.compareTo(str2);
  if (result < 0) {
    print('"$str1" is less than "$str2".');
  } else if (result > 0) {
    print('"$str1" is greater than "$str2".');
  } else {
    print('"$str1" is equal to "$str2".');
  }
}

Output

"apple" is less than "banana".

Conclusion

In this Dart Tutorial, we learned how to compare two Strings, using compareTo() method of String class, with examples.