find the nth occurence of a substring in a string in java?

后端 未结 5 2109
南旧
南旧 2021-01-13 10:48

I have a string that is the complete content of an html page and I am trying to find the index of 2nd occurence of . Does anyone have any suggesti

5条回答
  •  没有蜡笔的小新
    2021-01-13 11:51

    First find the first index, then look for the second index starting your search from the first index +1

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

    This is some pretty basic code btw, you will want to build some additional checks (index != -1 and the like) Also in your post title it said nth occurence but in your post you mention the second occurence specifically. I'm sure you'll be able to figure it out from here if you actually need the nth occurence though.

提交回复
热议问题