Course outline
Course / The terminal and the language

Count uppercase and lowercase

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/11-06-letter-case-counts
cd 11-06-letter-case-counts
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Finish two functions that count the upper-case and lower-case letters in Text. Use range to visit each character, and use continue to skip anything that is not a letter.

Example

If Text were "Go 2!", then UpperCount() is 1 (the G) and LowerCount() is 1 (the o). The space, the 2 and the ! are skipped, not counted.

Here is the same idea counting vowels, so you can see the shape:

func VowelCount() int {
	count := 0
	for _, r := range Text {
		if !unicode.IsLetter(r) {
			continue
		}
		if r == 'a' || r == 'e' || r == 'i' || r == 'o' || r == 'u' {
			count++
		}
	}
	return count
}

The counter is declared before the loop, so it builds up instead of resetting. continue ends a pass early for anything that is not a letter.

Rules

  • Edit letters.go. Add import "unicode" at the top of the file.
  • UpperCount returns how many upper-case letters are in Text. LowerCount returns how many lower-case letters.
  • In both functions, declare a counter before the loop and loop with for _, r := range Text.
  • Use continue to skip runes that are not letters. Digits, spaces and punctuation are never counted.
  • Use unicode.IsLetter, unicode.IsUpper and unicode.IsLower, so letters like É and é count too.
  • An empty Text gives 0 for both.
  • The tests change Text, so use the variable. Do not type text into the functions.
  • Do not change the var Text line or the first line of each function.

What you'll practice

range over a string, continue to skip a pass, and a counter declared before the loop.

Run it

gonomicon fetch week-1/11-06-letter-case-counts
cd 11-06-letter-case-counts
gonomicon test
gonomicon submit

Hints

  1. You need a counter that starts at 0 before the loop, then a loop that visits every rune of Text. Do this once in each function.
  2. Use for _, r := range Text. Inside, if r is not a letter, continue to skip it. Then if the letter is upper case (unicode.IsUpper), add 1 to the counter. LowerCount is the same with unicode.IsLower.
  3. count := 0, then for _, r := range Text { if !unicode.IsLetter(r) { continue }; if unicode.IsUpper(r) { count++ } }, then return count. Add import "unicode" at the top of the file.

Something wrong with this lesson? Report a problem