Working with Strings
At its heart, tally does one thing to text: turn a line like " The cat saw THE dog " into clean, lower-case words. That needs you to know what a string really is, and which tools in the strings package do the heavy lifting.
The rule
Strings are immutable bytes; every change makes a new string.
Bytes. A string is a sequence of bytes. len(s) counts them, s[i] returns one byte, and s[a:b] slices by byte positions:
s := "tally"
fmt.Println(s[0]) // 116, the byte for 't'
fmt.Println(s[1:4]) // allImmutable. You cannot change a string in place. s[0] = 'T' is a compile error. Every operation that "changes" text — +, strings.ToUpper, strings.ReplaceAll — returns a new string and leaves the old one untouched. That makes strings safe to share and cheap to pass around.
The strings package covers the daily work:
line := " The cat saw THE dog "
words := strings.Fields(strings.ToLower(line))
fmt.Println(words) // [the cat saw the dog]
fmt.Println(len(words)) // 5| Function | Result |
|---|---|
strings.Fields(s) |
splits on any run of whitespace, no empty pieces |
strings.Split(s, ",") |
splits on exactly that separator, keeping empty pieces |
strings.TrimSpace(s) |
removes leading and trailing whitespace |
strings.Contains(s, "cat") |
true if the text appears |
strings.Join(words, " ") |
glues a slice back together |
Strings compare with == and < (byte by byte, so "Zebra" < "apple" is true — capital letters sort first).
Building text in a loop? += makes a new string every time. strings.Builder grows one buffer instead:
var b strings.Builder
for _, w := range words {
b.WriteString(w)
b.WriteString(";")
}
fmt.Println(b.String()) // the;cat;saw;the;dog;The shortcut
For any text task, clean, split, then count — and reach for the strings package before writing a loop.
Clean
strings.ToLower(line)gives" the cat saw the dog ", a new string.
Drills
Answer fast — trust the rule.
What does s := "go"; s[0] = 'G' do?
What is len(strings.Fields(" a b c "))?
What does "tally"[1:3] give?
What is strings.Split("a,,b", ",")?
Which is true in Go?
Remember
- Strings are immutable bytes; every change makes a new string.
- Shortcut: clean, split, count — with the strings package.
- Trap:
Splitkeeps empty pieces;Fieldsdoes not.
