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

如何用icu4j将序数字符串(如FOURTH)转换为整数?

如何用icu4j将英文序数字符串转换为整数?

我需要把类似"FOURTH"这样的序数字符串转换成对应的整数4,尝试使用icu4j的RuleBasedNumberFormat实现,但以下代码返回0而不是预期的4:

RuleBasedNumberFormat formatter = new RuleBasedNumberFormat(Locale.US, RuleBasedNumberFormat.ORDINAL);
return formatter.parse("FOURTH").intValue();

解决方法

问题出在全大写的序数字符串不匹配RuleBasedNumberFormat默认的美式英语序数解析规则。默认规则只识别小写(如"fourth")或首字母大写(如"Fourth")的序数词,因此需要先将输入字符串转换为小写,再进行解析。

正确的实现代码如下:

import com.ibm.icu.text.RuleBasedNumberFormat;
import com.ibm.icu.util.ULocale;
import java.text.ParseException;

public class OrdinalToInteger {
    public static int convertOrdinalToInt(String ordinalStr) throws ParseException {
        // 使用ULocale确保icu4j的本地化支持更准确
        RuleBasedNumberFormat ordinalFormatter = new RuleBasedNumberFormat(ULocale.US, RuleBasedNumberFormat.ORDINAL);
        // 将输入转为小写后解析
        return ordinalFormatter.parse(ordinalStr.toLowerCase()).intValue();
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(convertOrdinalToInt("FOURTH")); // 输出4
        System.out.println(convertOrdinalToInt("TWENTY-FIRST")); // 输出21
    }
}

注意事项

  • 务必处理ParseException:如果输入的字符串不是有效的序数词(比如拼写错误),parse方法会抛出该异常,不要直接忽略,否则可能得到错误的默认值(如0)。
  • 推荐使用ULocale而非Java标准Locale:icu4j对ULocale的支持更完善,能避免一些本地化适配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:53:11