查看原文
其他

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

编程导航-松柏 程序员鱼皮 2024-04-08

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

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

该怎么做呢?

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

示例代码:

public static int indexOf(String text, String searchText, int n) {
  if (StrUtil.hasEmpty(text, searchText)) {
     throw new BusinessException(ErrorCode.PARAMS_ERROR, "有参数为空");
  }
  // 循环找到第 n 个换行符的位置
  int index = -1;
  int tempIndex = -1;
  for (int i = 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,示例代码:

int index = StrUtil.ordinalIndexOf(text, str, n);

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

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

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

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

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

往期推荐

今日代码 PK | 富文本转纯文本

今日代码 PK | 根据 code 获取小程序登录信息

今日代码 PK | 统一响应结果

今日代码 PK | 处理 Spring 事务和锁冲突

今日代码 PK | 使用 try-with-resources 关闭资源

继续滑动看下一个
向上滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存