当前位置: 欣欣网 > 码农

今日代码 PK | 获取字符第 n 次出现的位置

2024-03-27码农

在我们日常的开发中,免不了对字符串进行各种操作,

比如现在我需要获取某个字符串在一段文本中第 n 次出现的索引,

该怎么做呢?

大部分小伙伴会觉得并不难,直接就写了出来,

示例代码:

publicstaticintindexOf(String text, String searchText, int n) {
if (StrUtil.hasEmpty(text, searchText)) {
thrownewBusinessException(ErrorCode.PARAMS_ERROR, "有参数为空");
}
// 循环找到第 n 个换行符的位置
intindex = -1;
inttempIndex = -1;
for (inti = 0; i < text.length(); i++) {
tempIndex = text.indexOf(searchText, tempIndex + 1);
// tempIndex 等于 -1 text 中没有出现 n 次 searchText,直接返回 -1
if (tempIndex == -1) {
return -1;
}
if ((i + 1) == n) {
index = tempIndex;
return index;
}
}
return index;
}

但大家有没有想过,这种经典的场景会有现成的实现呢?

比如 hutool ,示例代码:

intindex = StrUtil.ordinalIndexOf(text, str, n);

本来我们需要一堆代码才能实现的功能,可能只需要一行代码就实现了。

你更喜欢哪种方式呢?欢迎投票并在评论区讨论。

完整代码片段来源于代码小抄,欢迎点击进入小程序阅读!

在线访问:https://www.codecopy.cn/post/66wxen

更多优质代码欢迎进入小程序查看!

往期推荐