This site requires JavaScript, please enable it in your browser!
Greenfoot back
Zweeg
Zweeg wrote ...

2018/11/29

How to find the index of the nth occurence of a given phrase in a string

Zweeg Zweeg

2018/11/29

#
Let's say I have the string "catdogcatdogcatdog". I want to find the index of the second occurence of "dog". How would I do this? I understand the usage of stringName.indexOf("phrase") but how I don't really see how I can use this method alone to find the index of the second or third occurrence.
danpost danpost

2018/11/30

#
There is another, actually 4, indexOf methods in the String class. Make use of stringName.indexOf("phrase", position) where position is where in stringName you want the search to start.
You need to login to post a reply.