/ Published in: Ruby

Public domain. Returns the nth occurrence of substring
within var
, or -1 if var
does not include n
substrings or if n
is negative. Does not account for overlapping substrings (one solution is to delimit substrings, such as with a space, so you can pass " or " as substring
to find occurrences of "or" as a word).
See also Find n from the index of the nth occurrence of a substring.
Expand |
Embed | Plain Text
def find_nth_occurrence(var, substring, n) position = -1 if n > 0 && var.include?(substring) # is n positive, and var includes substring i = 0 while i < n do position = var.index(substring, position+substring.length) if position != nil i += 1 end end return position != nil && position != -1 ? position + 1 : -1; # return the index of the nth occurrence of substring if it exists, otherwise -1 end
You need to login to post a comment.