Drills — write the functions
Reading about strings isn't enough — you have to write. Five tasks, from easy to harder. For each, write a function, run it on the examples, then compare with the solution. Try it yourself before looking.
1 (easy) — charCount. Return the real character count (not bytes).
charCount("ąžuolas") → 7 charCount("obuolys") → 7
func charCount(s string) int {
return utf8.RuneCountInString(s)
}
2 (easy) — initials. From "Jonas Jonaitis" make "JJ": the first letter of each word, uppercased.
initials("Jonas Jonaitis") → "JJ" initials("ąžuolas uosis") → "ĄU"
func initials(fullName string) string {
var b strings.Builder
for _, word := range strings.Fields(fullName) { // Fields splits on whitespace
r := []rune(word)
b.WriteString(strings.ToUpper(string(r[0]))) // r[0] = the first CHARACTER
}
return b.String()
}
3 (medium) — truncateRunes. Cut to max characters and add "…" if longer. Important: don't cut "ą" in half.
truncateRunes("ąžuolynas prie ežero", 9) → "ąžuolynas…"
truncateRunes("Go", 9) → "Go"
func truncateRunes(s string, max int) string {
r := []rune(s)
if len(r) <= max {
return s
}
return string(r[:max]) + "…"
}
4 (medium) — slug. Make a "link" form: lowercase, spaces → hyphens, no edge spaces.
slug(" The Go Language ") → "the-go-language"
func slug(title string) string {
return strings.ReplaceAll(strings.ToLower(strings.TrimSpace(title)), " ", "-")
}
5 (harder) — banner with strings.Builder. Return s repeated n times, using Builder (not += in a loop).
banner("=", 5) → "=====" banner("ab", 3) → "ababab"
func banner(s string, n int) string {
var b strings.Builder
for i := 0; i < n; i++ {
b.WriteString(s)
}
return b.String()
}
Tip. Call each function from
maintemporarily (fmt.Println(charCount("ąžuolas"))) and check it against the examples. These small, "pure" functions (no input, no state) are exactly the kind we'll test automatically withgo testin lesson 13.