Posted By

jatkins on 06/26/10


Tagged

index substring


Versions (?)

Find the nth occurrence of a substring


 / 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.

  1. def find_nth_occurrence(var, substring, n)
  2. position = -1
  3. if n > 0 && var.include?(substring) # is n positive, and var includes substring
  4. i = 0
  5. while i < n do
  6. position = var.index(substring, position+substring.length) if position != nil
  7. i += 1
  8. end
  9. end
  10. return position != nil && position != -1 ? position + 1 : -1; # return the index of the nth occurrence of substring if it exists, otherwise -1
  11. end

Report this snippet  

You need to login to post a comment.