Code Lab

Count characters in a sentence

MediumMap and Set10 min

Write a function countCharacters(sentence) that counts how many times every character occurs in a sentence.

  • sentence is a string. It can be empty.
  • Return a Map: the key is the character, the value is its count.
  • Case does not matter: 'A' and 'a' are the same character. Put letters into the Map in lower case. This is a case insensitive count.
  • Do not count whitespace: spaces, tabs ('\t') and new lines ('\n').
  • Count everything else: punctuation marks and digits too.
  • If there is nothing to count, return an empty Map.
  • Key order is not checked.

Examples

countCharacters('Hi hi')

Returns Map(2) { 'h' => 2, 'i' => 2 }

countCharacters('Aa, 1!')

Returns Map(4) { 'a' => 2, ',' => 1, '1' => 1, '!' => 1 }

countCharacters('   ')

Returns Map(0) {}

Asked at Arcesium · Source

Loading the editor...
  1. InputcountCharacters('Hello World')
    ExpectedMap(7) { 'h' => 1, 'e' => 1, 'l' => 3, 'o' => 2, 'w' => 1, 'r' => 1, 'd' => 1 }
  2. InputcountCharacters('a.b.a')
    ExpectedMap(3) { 'a' => 2, '.' => 2, 'b' => 1 }

Hidden tests run on Submit.