Boss lesson · Unit 03
A text toolkit
Three small functions on text: a palindrome check, a vowel counter and a Caesar shift.
What you practise
- Small functions built and combined: a palindrome check, a vowel counter, a Caesar shift over bytes and runes, each checked against answers you know
Try a question from this lesson
Pick one
Text has positions, counted from 0. len gives its length, and square brackets pick out one position. What does this print?
word := "level"
fmt.Println(len(word), word[0] == word[4])Correct answer
5 true
Why
"level" has 5 characters, at positions 0 to 4. Position 0 holds l and position 4 holds l, so the comparison is true. The last position is always one less than the length.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Strings, one position at a time
len(s) is the length of a string. s[i] is what sits at position i, counting from 0.
What you get is a byte: a small whole number that stands for a character. A character in single quotes, like 'g', is that number written readably. string(...) turns a byte back into text.
s := "go"
fmt.Println(len(s)) // 2
fmt.Println(s[0] == 'g') // true
fmt.Println(string(s[1])) // oConcept
A switch with several values
One case can list several values, separated by commas. It matches if the value equals any of them.
That makes a neat test for vowels. The parameter is a byte, the type you get from s[i], and each letter in single quotes is a byte too.
func isVowel(b byte) bool {
switch b {
case 'a', 'e', 'i', 'o', 'u':
return true
}
return false
}
fmt.Println(isVowel('e'), isVowel('x'))Concept
Letters are numbers
Bytes are numbers, so you can calculate with letters. The lowercase letters are numbered in order, so b - 'a' is the place of a letter in the alphabet: 0 for a, 1 for b, up to 25 for z.
A Caesar shift, a very old secret code, moves every letter a fixed number of places along. % 26 makes a place past z wrap round to the start.
b := byte('y')
pos := (b - 'a' + 3) % 26
fmt.Println(pos) // 1
fmt.Println(string('a' + pos)) // b9 more exercises in the app
- 4× type the answer
- 2× fill the blanks
- 1× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.