有没有一种方法可以按字符串中的数字对字符串列表进行排序?

时间:2020-04-25 23:40:42

标签: flutter dart

是否可以对类似的东西进行排序:

<script>
    $(document).on('DOMSubtreeModified', 'body', function (el) {
        console.log('body content changed');
        // append you init code here
    });
</script>

对此吗?

List<String> hi = ['1hi', '2hi','5hi', '3hi', '4hi'];

2 个答案:

答案 0 :(得分:4)

仅调用List<String>.sort()就会执行lexical sort。也就是说,您的字符串将按字符代码顺序排序,而'10'将在'2'之前排序。通常这是意料之外的。

如果您的数字的前导0可以确保所有数字具有相同的数字,那么 便可以进行词汇排序。但是,如果数字位数是可变的,则需要 parse 进行排序。一种更通用的方法是提供对.sort()的回调,以告诉它如何确定两个项目的相对顺序。

幸运的是,package:collection具有compareNatural功能可以为您完成此操作:

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);
}

答案 1 :(得分:1)

您可以像这样对列表进行排序:

hi.sort();

(因为数字在其实现中排在字母的前面)

相关问题