Hutool 5.8.15 版本中查找字符串所有位置的解决方法
在 Hutool 5.8.15 版本中,确实没有提供 'StrUtil.indexOfAll' 方法。但是你可以使用 Java 自带的 String 类来实现查询字符串中包含一个字符串的所有位置。
你可以使用 String 类的 'indexOf' 方法来查找字符串中第一次出现子字符串的位置,然后使用 while 循环不断查找后面的位置,直到找不到为止。
下面是一个示例代码:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String str = 'hello world hello';
String target = 'hello';
List<Integer> positions = new ArrayList<>();
int index = str.indexOf(target);
while (index >= 0) {
positions.add(index);
index = str.indexOf(target, index + 1);
}
System.out.println('Positions: ' + positions);
}
}
输出结果为:Positions: [0, 12],表示字符串中包含 'hello' 的位置分别为 0 和 12。
你可以替换 str 和 target 的值来测试不同的字符串和目标子字符串。
原文地址: http://www.cveoy.top/t/topic/pkzq 著作权归作者所有。请勿转载和采集!