且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在字符串中找到第n个字符?

更新时间:2023-02-04 23:22:54

如果您的项目已经依赖于Apache Commons,您可以使用 StringUtils.ordinalIndexOf ,否则,这是一个实现:

If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf, otherwise, here's an implementation:

public static int ordinalIndexOf(String str, String substr, int n) {
    int pos = str.indexOf(substr);
    while (--n > 0 && pos != -1)
        pos = str.indexOf(substr, pos + 1);
    return pos;
}






此帖子已被重写作为此处的文章。