No Recursive instr?!!

A

Anil Gupte

I must have missed it. It cannot be possible. Or may be I am living in the
past of my lisp programming days.

There must be a function to find the nth occurrence of a string within
another. instr only gives you the first one. Of course I can write a
function that recurses n times to get the nth occurrence, but there must be
a native version, right? To clarify, lets say I want the 3rd x in this
string:

strMine="xxoooxoxoxo"

instrNth=(strMine, "x", 3)
returning 6

Any ideas?
 
M

Maate

Depending on your case, I guess you can profit from regex? e.g.:

dim re as regex = new regex(pattern, regexoptions.multiline) ' e.g.
pattern = "x"
dim myMatches as matchcollection = re.matches(source-string) 'e.g.
source-string = "xxooxoxoxo"

myMatches(n) = n'th occurrence of some match 'e.g. myMatches(2) = x
myMatches(n).index = the index of the n'th occ. 'e.g.
myMatches(2).index = 4

anyway - it's more pretty than writing a recursive instr function, I
guess...



Anil Gupte skrev:
 
H

Herfried K. Wagner [MVP]

Anil Gupte said:
I must have missed it. It cannot be possible. Or may be I am living in
the past of my lisp programming days.

There must be a function to find the nth occurrence of a string within
another. instr only gives you the first one. Of course I can write a
function that recurses n times to get the nth occurrence, but there must
be a native version, right? To clarify, lets say I want the 3rd x in this
string:

I'd use the iterative approach: Call 'InStr' until either the end of the
string is reached or the n-th occurance has been found.
 
A

Anil Gupte

Wow! Regex is quite comprehensive - I will have to sit down and study it
for a while, before I can use it.

Thanx!
--
Anil Gupte
www.keeninc.net
www.icinema.com

Maate said:
Depending on your case, I guess you can profit from regex? e.g.:

dim re as regex = new regex(pattern, regexoptions.multiline) ' e.g.
pattern = "x"
dim myMatches as matchcollection = re.matches(source-string) 'e.g.
source-string = "xxooxoxoxo"

myMatches(n) = n'th occurrence of some match 'e.g. myMatches(2) = x
myMatches(n).index = the index of the n'th occ. 'e.g.
myMatches(2).index = 4

anyway - it's more pretty than writing a recursive instr function, I
guess...



Anil Gupte skrev:
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top