How do I compare String with case insensitivity, in Dart?

How do I compare two strings in Dart with case insensitivity?

For example, I have this list:

var list = ['Banana', 'apple'];

      

And I would like to sort it in such a way that it is apple

before Banana

.

Final result:

['apple', 'Banana'];

      

+13


source to share


4 answers


There is no case-insensitive string comparison function in Dart (or string equality function). Mainly because it is difficult and there is no single good solution we would like to fix.

The problem is that the correct way to do case-insensitive comparison is to use full folding in Unicode ( http://www.w3.org/International/wiki/Case_folding ) along with (possibly locale-specific) order of the resulting Unicode characters. Unicode characters can span multiple code points and can have different representations, so you probably want to do other Unicode normalizations as well.

So it's terribly difficult and requires a fairly large table.

Great if you already have a complete Unicode library, less great if you want to compile small JavaScript code.



Even if you just use ASCII, you still have to figure out what the order should be. Is Z

& lt; ^

? (As ASCII codes, they are). Is ^

& lt; a

? Again, like ASCII codes, they are. But you probably don't want Z

& lt; a

compared to a case-insensitive, so for consistency you need to convert to upper or lower case, and the one you choose will change its attitude a

and ^

to each other.

The package collection

has a compareAsciiUpperCase function (and similar for lowercase), but it package:quiver

has a function compareIgnoreCase

that simply executes toLowerCase()

on both arguments. You can use it like:

import "package:collection/collection.dart";
...
   list.sort(compareAsciiUpperCase);

      

+10


source


There is no built-in case-insensitive way to compare strings in dart ( as @lrn answered ).

If you want to compare strings in a case insensitive manner, I would settle for declaring the following method somewhere in the usual place:

bool equalsIgnoreCase(String string1, String string2) {
  return string1?.toLowerCase() == string2?.toLowerCase();
}

      



Example:

equalsIgnoreCase("ABC", "abc"); // -> true
equalsIgnoreCase("123" "abc");  // -> false
equalsIgnoreCase(null, "abc");  // -> false
equalsIgnoreCase(null, null);   // -> true

      

+9


source


One way to do this, you can uppercase your strings in the sort () method:

list.sort((a, b) => a.toUpperCase().compareTo(b.toUpperCase()));

      

+3


source


You can use Google's own string bundle . It has equalsIgnoreCase function . And here is its implementation:

bool equalsIgnoreCase(String a, String b) =>
    (a == null && b == null) ||
    (a != null && b != null && a.toLowerCase() == b.toLowerCase());

      

-1


source







All Articles