获取给定文本字符串的搜索短语的所有字符位置的最佳方法是什么?
例如,假设我们有"the red cat is watching the red car stopped at the red stop sign"
输入:“红色”输出:[5, 29, 52]
获取给定文本字符串的搜索短语的所有字符位置的最佳方法是什么?
例如,假设我们有"the red cat is watching the red car stopped at the red stop sign"
输入:“红色”输出:[5, 29, 52]
您可以使用字符串类的indexOf方法:
String haystack = "the red cat is watching the red car stopped at the red stop sign";
String needle = "red";
int idx = 0, pos;
while( (pos = haystack.indexOf(needle,idx)) != -1) {
System.out.println(pos+1);
idx += pos+1;
}