只是打电话List<String>.sort()
本身会做一个词典编法 sort https://en.wikipedia.org/wiki/Lexicographic_order。也就是说,您的字符串将按字符代码顺序排序,并且'10'
之前会排序'2'
。这通常是意想不到的。
字典排序将起作用if你的数字领先0
确保所有数字具有相同的位数。但是,如果位数可变,则需要parse用于排序的数字的值。更通用的方法是提供回调.sort()
告诉它如何确定两个项目的相对顺序。
幸运的是,package:collection https://pub.dev/packages/collection has a compareNatural https://pub.dev/documentation/collection/latest/collection/compareNatural.html可以为您执行此操作的函数:
import 'package:collection/collection.dart';
List<String> hi = ['1hi', '2hi','5hi', '3hi', '4hi'];
hi.sort(compareNatural);
如果你的情况有点复杂并且compareNatural
没有做你想做的事,更通用的方法是使.sort()
回调会解析自身,例如通过正则表达式:
/// Returns the integer prefix from a string.
///
/// Returns null if no integer prefix is found.
int parseIntPrefix(String s) {
var re = RegExp(r'(-?[0-9]+).*');
var match = re.firstMatch(s);
if (match == null) {
return null;
}
return int.parse(match.group(1));
}
int compareIntPrefixes(String a, String b) {
var aValue = parseIntPrefix(a);
var bValue = parseIntPrefix(b);
if (aValue != null && bValue != null) {
return aValue - bValue;
}
if (aValue == null && bValue == null) {
// If neither string has an integer prefix, sort the strings lexically.
return a.compareTo(b);
}
// Sort strings with integer prefixes before strings without.
if (aValue == null) {
return 1;
} else {
return -1;
}
}
void main() {
List<String> hi = ['1hi', '2hi','5hi', '3hi', '4hi'];
hi.sort(compareIntPrefixes);
}