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

Groovy中ordinalIndexOf()无法使用的原因及正确用法咨询

关于Groovy中ordinalIndexOf()方法的问题解答

你遇到的这个报错很典型——Java和Groovy原生的String类根本没有ordinalIndexOf()这个方法,所以直接在字符串对象上调用它肯定会抛出MissingMethodException。

正确使用的两种方式:

1. 使用Apache Commons Lang库的StringUtils.ordinalIndexOf()

这个方法是第三方工具库Apache Commons Lang提供的,需要先引入依赖才能用:

  • 如果是Groovy脚本,用@Grab快速引入:
@Grab('org.apache.commons:commons-lang3:3.14.0')
import org.apache.commons.lang3.StringUtils

// 调用方式:StringUtils.ordinalIndexOf(原字符串, 子串, 第n次出现)
println StringUtils.ordinalIndexOf('hello', 'l', 1) // 输出1(第1次出现的'l'的索引)
println StringUtils.ordinalIndexOf('hello', 'l', 2) // 输出2(第2次出现的'l'的索引)

2. 自己扩展String的元类(无需第三方库)

如果你不想引入外部依赖,可以给Groovy的String类动态添加这个方法:

// 扩展String元类,添加ordinalIndexOf方法
String.metaClass.ordinalIndexOf = { String subStr, int n ->
    int count = 0
    int currentIndex = -1
    while (count < n) {
        currentIndex = delegate.indexOf(subStr, currentIndex + 1)
        if (currentIndex == -1) break // 找不到足够次数的子串,直接退出
        count++
    }
    return count == n ? currentIndex : -1 // 找到返回索引,没找到返回-1
}

// 现在就可以像原生方法一样调用了
println 'hello'.ordinalIndexOf('l', 1) // 输出1
println 'hello'.ordinalIndexOf('l', 2) // 输出2
println 'hello'.ordinalIndexOf('x', 1) // 输出-1(找不到子串)

简单总结下:你之前的问题就是把第三方库的方法当成了String的原生方法来调用,只要补上依赖或者自己实现扩展,就能正常使用啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:13:22