Skip to content
ExamSpine

Lesson 5.4 · Write it

Count a letter

A functionPython or Java9 tests, 6 of them hidden

On a phone? Put the lines in order instead

Write a function that returns how many times a letter appears in a piece of text, ignoring upper and lower case.

  1. letter is always one letter from A to Z, in either case. In Python it is a text value of one letter; in Java it is a char.
  2. Upper and lower case count as the same letter, whichever way round: A in the text matches the letter a, and a in the text matches the letter A.
  3. The text contains only English letters, digits, spaces and punctuation, and can be empty. Digits, spaces and punctuation never match a letter.

Only the number your function returns is checked.

def count_letter(text: str, letter: str) -> int

Examples

Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.

  • count_letter("Bob", "b") should return 2: a capital B in the text matches the letter b, and so does the b at the very end (rule 2)
  • count_letter("Mississippi", "S") should return 4: an upper-case letter still matches lower-case text (rule 2)
  • count_letter("", "x") should return 0: empty text (rule 3)

public static int countLetter(String text, char letter)

Checking whether Java answers can run here.

Examples

Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.

  • countLetter("Bob", 'b') should return 2: a capital B in the text matches the letter b, and so does the b at the very end (rule 2)
  • countLetter("Mississippi", 'S') should return 4: an upper-case letter still matches lower-case text (rule 2)
  • countLetter("", 'x') should return 0: empty text (rule 3)
solution.pySolution.java