HuTool 字符串查找:获取所有匹配位置
可以使用 HuTool 中的 StrUtil 类中的 'indexOfAll' 方法来查询字符串中包含一个字符串的所有位置。
具体代码如下:
import cn.hutool.core.util.StrUtil;
public class Main {
public static void main(String[] args) {
String str = 'hello world hello';
String keyword = 'hello';
int[] indexes = StrUtil.indexOfAll(str, keyword);
for (int index : indexes) {
System.out.println('Found at index: ' + index);
}
}
}
输出结果如下:
Found at index: 0
Found at index: 12
以上代码使用 'StrUtil.indexOfAll' 方法来查询字符串 'str' 中包含字符串 'keyword' 的所有位置,并打印出每个位置的索引值。在上述示例中,字符串 'str' 中有两个 'hello',分别位于索引 0 和索引 12 处。
原文地址: http://www.cveoy.top/t/topic/pky1 著作权归作者所有。请勿转载和采集!