标签: java regex string-matching indexof
获取给定文本字符串的搜索短语的所有字符位置的最佳方法是什么?
例如,我们说"the red cat is watching the red car stopped at the red stop sign"
"the red cat is watching the red car stopped at the red stop sign"
输入:“红色” 输出:[5,29,52]
答案 0 :(得分:2)
您可以使用字符串类的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; }
See it