统计字母出现的次数

2015-12-07 0 467
统计字母出现的次数
#Counts the number of times a 'letter' appears in a 'phrase'
def CountLetterOccurrence(letter, phrase, matchCase)
  # Gets the length of the phrase
  index = phrase.length
  # Splits the string into an array getting all of the characters from the phrase
  array = phrase.split(//)
  # Placeholder for how many letters that we find a match to
  count = 0
  # Loop through the array
  array.each do |character|
    # If we care about the letter CAsINg
    if matchCase == true
      # If the current character is the letter we are trying to find
      if character == letter
        # 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 character is the letter we are trying to find
      if character.downcase == letter.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 letters matched
  return count
  # Exit the method
end

遇见资源网 ruby 统计字母出现的次数 http://www.ox520.com/16555.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务