0 Replies - 1425 Views - Last Post: 16 October 2009 - 01:27 PM

#1 gbertoli3   User is offline

  • DIC at Heart + Code
  • member icon

Reputation: 41
  • View blog
  • Posts: 1,166
  • Joined: 23-June 08

Count the Occurrence of a Word

Posted 16 October 2009 - 01:27 PM

Description: Use: # Use this if you do not care about word CAsINg CountWordOccurrence("world", "Hello World", false) # Use this if you do care about word CAsINg CountWordOccurrence("World", "Hello World", true)Counts the number of times a word occurs in a phrase with cAsE SenSiTivItY option.
#Counts the number of times a 'word' appears in a 'phrase'
def CountWordOccurrence(word, phrase, matchCase)
  # Gets the length of the phrase
  index = phrase.length
  # Splits the string into an array getting all of the words from the phrase
  array = phrase.split(' ')
  # Placeholder for how many words that we find a match to
  count = 0
  # Loop through the array
  array.each do |item|
    # If we care about the word CAsINg
    if matchCase == true
      # If the current item is the word we are trying to find and has same CAsINg
      if item == word
        # Add 1 to the count
        count = count + 1
        # Exit the if statement
      end
      # If we do not care about the word CAsINg
    else
      # If the current item is the word we are trying to find CAsINg doesn't matter
      if item.downcase == word.downcase
        # Add 1 to the count
        count = count + 1
        # Exit the if statement
      end
      # Exit the if statement
    end
      # Exit the loop
    end
  # Return the number of words matched
  return count
  # Exit the method
end



Is This A Good Question/Topic? 0
  • +

Page 1 of 1