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.
letteris always one letter from A to Z, in either case. In Python it is a text value of one letter; in Java it is achar.- Upper and lower case count as the same letter, whichever way round:
Ain the text matches the lettera, andain the text matches the letterA. - 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)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.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)