How to count the number of non-overlapping instances of a substring in a string in Ruby

1 Answer

0 votes
# Non‑overlapping occurrences are matches of a substring that do not reuse any of 
# the same characters. Once one match is counted, the next search must begin 
# after that match ends.

def count_non_overlapping(haystack, needle)
  """
  Count how many times 'needle' appears in 'haystack' without overlapping.
  The algorithm:
    • Use index() to locate the next occurrence.
    • Each time a match is found, move the search index forward
      by the full length of the matched substring.
    • This ensures no characters are reused between matches.
  """

  count = 0
  index = 0  # current search position in the main string

  # Continue searching until index() returns nil (meaning: no more matches)
  loop do
    # Find the next occurrence starting at the current index
    pos = haystack.index(needle, index)

    if pos.nil?
      # No more matches found
      break
    end

    # We found a match, so increment the count
    count += 1

    # Move index forward by the length of the needle
    # This ensures the next search begins *after* the matched substring
    index = pos + needle.length
  end

  return count
end


# ---------------------------------------------------------------
s = 'go java phphp rust c pphpp c++ phpphp python php phphp'
substring = 'php'

# Count non-overlapping occurrences
result = count_non_overlapping(s, substring)

puts "Non-overlapping occurrences: #{result}"


=begin
run:

Non-overlapping occurrences: 6

=end

 



answered Jul 18 by avibootz

Related questions

...