Over a million developers have joined DZone.

Count Characters

·
// Sample Output, "character (byte) occurs n times", 32 = space
// s (115) occurs 3 times
// n (110) occurs 1 times
// ..
//   (32) occurs 3 times


class Counter
  
def initialize()
  @characters = Hash.new(0)
end

def read()
  @text = IO.read("text.txt")
end

def count_chars
  @text.each_byte do |ch|
  @characters[ch] +=1
  end
end

def report  
  @characters.each do |key, value|
    puts "#{key.chr} (#{key}) occurs #{value} times"
  end  
end

end




// usage

count = Counter.new()
count.read
count.count_chars
count.report
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}