如何比较Dart中的两个字符串,不区分大小写?
例如,我有这个列表:
var list = ['Banana', 'apple'];
Run Code Online (Sandbox Code Playgroud)
而且我想在此apple之前对其进行排序Banana.
最终结果:
['apple', 'Banana'];
Run Code Online (Sandbox Code Playgroud)
Roh*_*eja 13
您可以创建一个扩展函数:
extension StringExtensions on String {
bool containsIgnoreCase(String secondString) => this.toLowerCase().contains(secondString.toLowerCase());
//bool isNotBlank() => this != null && this.isNotEmpty;
}
Run Code Online (Sandbox Code Playgroud)
用法:
if ("abcd".containsIgnoreCase("AB")) {
//true
}
Run Code Online (Sandbox Code Playgroud)
Set*_*add 10
一种方法是,您可以在 sort() 方法中将字符串大写:
list.sort((a, b) => a.toUpperCase().compareTo(b.toUpperCase()));
Run Code Online (Sandbox Code Playgroud)
lrn*_*lrn 10
Dart中没有不区分大小写的字符串比较函数(或者字符串相等函数).基本上因为它很难,而且没有一个好的解决方案我们想要修复.
问题是进行不区分大小写的比较的正确方法是使用完整的Unicode case-folding(http://www.w3.org/International/wiki/Case_folding)以及(可能是特定于语言环境的)排序产生的Unicode字符.Unicode字符可能占用多个代码点,并且可以具有不同的表示形式,因此您可能还希望执行其他Unicode规范化.
所以,它非常复杂,需要一个相当大的表.
如果你已经拥有一个完整的Unicode库,那就太好了,如果你想编译成小的JavaScript代码那就不那么好了.
即使你只使用ASCII,你仍然需要弄清楚你想要的订单.是Z< ^?(作为ASCII码,它们是).是^< a?同样,作为ASCII码,它们是.但是你可能不希望Z< a在不区分大小写的比较中,所以为了保持一致性,你需要转换为大写或小写,你选择哪一个将改变方式a并相互^比较.
该collection包具有compareAsciiUpperCase函数(对于小写类似),并且package:quiver具有compareIgnoreCase仅toLowerCase()在两个参数上执行的函数.您可以将其用作:
import "package:collection/collection.dart";
...
list.sort(compareAsciiUpperCase);
Run Code Online (Sandbox Code Playgroud)
Jos*_*ush 10
没有内置的方式可以比较dart中不区分大小写的字符串(如@lrn回答)。
如果您只想比较不区分大小写的字符串,则可以在一个普通的地方声明以下方法:
bool equalsIgnoreCase(String string1, String string2) {
return string1?.toLowerCase() == string2?.toLowerCase();
}
Run Code Online (Sandbox Code Playgroud)
例:
equalsIgnoreCase("ABC", "abc"); // -> true
equalsIgnoreCase("123" "abc"); // -> false
equalsIgnoreCase(null, "abc"); // -> false
equalsIgnoreCase(null, null); // -> true
Run Code Online (Sandbox Code Playgroud)
您可以使用 Google 自己的quiver strings包。它有一个equalsIgnoreCase函数。这是它的实现:
当允许 null 时:
bool equalsIgnoreCase(String? a, String? b) =>
(a == null && b == null) ||
(a != null && b != null && a.toLowerCase() == b.toLowerCase());
Run Code Online (Sandbox Code Playgroud)
当不允许 null 时:
bool equalsIgnoreCase(String a, String b) => a.toLowerCase() == b.toLowerCase();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5396 次 |
| 最近记录: |