How to find the starting index of all occurrences of a word in a string in Ruby

1 Answer

0 votes
#
# Find all starting indices of a word inside a larger text.
# This function uses String#index in a loop. The method is efficient
# because Ruby implements substring search in optimized C code.
#
def find_all_occurrences(text, word)
  indices = []

  # Searching for an empty word is meaningless
  return indices if word.empty?

  start_pos = 0

  #
  # Loop:
  # - Search for the word starting at `start_pos`.
  # - If found, record the index.
  # - Move forward by one character to allow overlapping matches.
  #
  while (index = text.index(word, start_pos))
    indices << index
    start_pos = index + 1
  end

  indices
end

# Example usage
text = "the quick brown fox jumps over the lazy dog. the fox is clever."
word = "the"

puts "Text: #{text}"
puts "Word: \"#{word}\"\n\n"
puts "Occurrences at indices:"

find_all_occurrences(text, word).each do |idx|
  puts idx
end



#
# run:
#
# Text: the quick brown fox jumps over the lazy dog. the fox is clever.
# Word: "the"
#
# Occurrences at indices:
# 0
# 31
# 45
#

 



answered Aug 30 by avibootz
edited Aug 30 by avibootz

Related questions

...