You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取序数?怎样将指定Python序数计算代码转换为Dart实现

序数获取功能Dart实现

原Python代码通过字符串切片的精简逻辑实现了英文序数后缀的拼接,核心规则是:

  1. 数字后两位为11/12/13时,固定使用th后缀
  2. 其他情况按个位匹配:个位1→st、个位2→nd、个位3→rd、其他→th

完全对齐原Python逻辑的实现版本

String ordinal(int n) {
  const suffixBase = "tsnrhtdd";
  final int offset = ((n ~/ 10 % 10 != 1) && (n % 10 < 4)) ? n % 10 : 0;
  final suffix = "${suffixBase[offset]}${suffixBase[offset + 4]}";
  return "$n$suffix";
}

更高可读性的实现版本

更便于后续维护和规则调整:

String ordinal(int n) {
  // 处理11/12/13的特殊情况
  if (n ~/ 10 % 10 == 1) {
    return "${n}th";
  }
  // 按个位匹配后缀
  switch (n % 10) {
    case 1:
      return "${n}st";
    case 2:
      return "${n}nd";
    case 3:
      return "${n}rd";
    default:
      return "${n}th";
  }
}

两种实现输出效果完全一致,示例结果:

  • ordinal(1) → 1st
  • ordinal(11) → 11th
  • ordinal(23) → 23rd
  • ordinal(42) → 42nd
  • ordinal(100) → 100th

内容的提问来源于stack exchange,提问作者oceanmanta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 22:45:04