在java中查找字符串中子串的第n个出现位置?

我有一个字符串,它是html页面的完整内容,我正在尝试找到

的第二次出现的索引。 有没有人对如何实现这一点有任何建议?

这是一个有趣的镜头;)

 public static int findNthIndexOf (String str, String needle, int occurence) throws IndexOutOfBoundsException { int index = -1; Pattern p = Pattern.compile(needle, Pattern.MULTILINE); Matcher m = p.matcher(str); while(m.find()) { if (--occurence == 0) { index = m.start(); break; } } if (index < 0) throw new IndexOutOfBoundsException(); return index; } 

使用indexOf概括了@BasVanDenBroek的答案 :

 public static int nthIndexOf(String source, String sought, int n) { int index = source.indexOf(sought); if (index == -1) return -1; for (int i = 1; i < n; i++) { index = source.indexOf(sought, index + 1); if (index == -1) return -1; } return index; } 

快速而肮脏的测试:

 public static void main(String[] args) throws InterruptedException { System.out.println(nthIndexOf("abc abc abc", "abc", 1)); System.out.println(nthIndexOf("abc abc abc", "abc", 2)); System.out.println(nthIndexOf("abcabcabc", "abc", 2)); System.out.println(nthIndexOf("abcabcabc", "abc", 3)); System.out.println(nthIndexOf("abc abc abc", "abc", 3)); System.out.println(nthIndexOf("abc abc defasabc", "abc", 3)); System.out.println(nthIndexOf("abc abc defasabc", "abc", 4)); } 

找到第N个String的另一个好方法是使用Apache Commons的StringUtils.ordinalIndexOf() :

 StringUtils.ordinalIndexOf("aabaabaa", "b", 2) == 5 

首先找到第一个索引,然后查找从第一个索引+1开始搜索的第二个索引

 String string = "firstsecond"; int firstIndex = string.indexOf(""); int secondIndex = string.indexOf("", firstIndex+1); System.out.println("second index: " + secondIndex); 

这是一些非常基本的代码btw,你会想要建立一些额外的检查(索引!= -1等)同样在你的post标题中它说nth出现但在你的post中你特别提到了第二次出现。 如果你真的需要第n次出现,我相信你能从这里弄明白。

在https://stackoverflow.com/a/5678546/15789和https://stackoverflow.com/a/14356988/15789上进一步工作(感谢@ sebastiaan-van-den-broek和@assylias的原创海报)。

获取数组中的所有索引。 然后你可以获得任何第n个索引。 在许多情况下,可能需要多次获取字符串中子字符串的第n个索引。 获取一次数组并多次访问它可能会更容易。

 public static int[] getIndices(String source, String substr) { List indicesList = null; int index = source.indexOf(substr); if (index == -1) { return new int[0]; } else { indicesList = new ArrayList<>(); indicesList.add(index); } while (index != -1) { index = source.indexOf(substr, index + 1); if (index != -1) { indicesList.add(index); } } // Integer[] iarr = new int[1]; //Autoboxing does not work with arrays. Run loop to convert. //toArray does not convert Integer[] to int[] int[] indices = new int[indicesList.size()]; for (int i = 0; i < indicesList.size(); i++) { indices[i] = indicesList.get(i); } return indices; }