← 中文资源

简体中文版本

数字的序数后缀

把名次格式化成 1st/2nd/3rd 这样的序数后缀:末位 1/2/3 加 st/nd/rd,但 11th、12th、13th 一律按 th 处理。

阅读英文原文

实现说明

数字的序数后缀可以归结为类 OrdinalSuffix和函数 ordinalSuffix、main。 这个示例中仅有的重复出现在 for (long n : samples) 里。

使用要点

  • 执行文件,main 会按顺序走完 ordinalSuffix。

常见问题

「数字的序数后缀」这个示例怎么运行?

直接执行即可——程序只依赖运行时自身。

主签名形如 static String ordinalSuffix(long number)

核心语句

return switch ((int) (number % 10)) {
    case 1 -> "st";
    case 2 -> "nd";
    case 3 -> "rd";
    default -> "th";
};
return "th";

代码示例

public class OrdinalSuffix {

    // ordinal suffixes: 1st, 2nd, 3rd, but 11th/12th/13th break the last-digit rule
    static String ordinalSuffix(long number) {
        if (number % 100 >= 11 && number % 100 <= 13) {
            return "th";
        }
        return switch ((int) (number % 10)) {
            case 1 -> "st";
            case 2 -> "nd";
            case 3 -> "rd";
            default -> "th";
        };
    }

    public static void main(String[] args) {
        long[] samples = {1, 2, 3, 4, 11, 12, 13, 21, 22, 23, 101, 111, 1002};
        for (long n : samples) {
            System.out.println(n + ordinalSuffix(n));
        }
    }
}