Public domain. Returns the nth occurrence of
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).
- 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
- return position != nil && position != -1 ? position + 1 : -1; # return the index of the nth occurrence of substring if it exists, otherwise -1
You need to login to post a comment.