1. Recall the string model in Go
When you first start programming, a string feels like a “list of letters”. In Go, that impression quickly collides with reality: a string is a sequence of bytes, and most often those bytes represent text in UTF-8. This is not pedantry for the sake of pedantry: if you understand once “what a string is made of”, you will stop chasing strange bugs like “why is len("hello") not 6” and “why is s[0] not a letter”.
Go as a language generally likes to simplify life through constraints: for example, Go source files must be UTF-8 so that tools and the compiler do not live in a world of “what if this is UTF-16 with a BOM and a bit of Latin thrown in”. This fits the normalization idea well: we agree on a format in advance so that the code later is simpler and more reliable.
Key properties of string that we keep in mind:
- a string is immutable;
- len(s) gives the number of bytes, not “characters”;
- indexing s[i] gives one byte, not a “character”;
- for range over a string iterates over runes (Unicode code points), reading UTF-8.
To make this stick, here is a small example that simultaneously shows “bytes vs runes” and why a “heart” can take more than one byte.
package main
import "fmt"
func main() {
s := "Go❤️"
fmt.Println(len(s)) // 6 (bytes)
cnt := 0
for range s {
cnt++
}
fmt.Println(cnt) // 3 (runes)
}
len, indexing, and range: three views of a string
Usually, problems with strings appear not because strings are complicated, but because we accidentally use the wrong viewpoint. For example, you wanted the “first character” but got the “first byte”. You wanted the “number of letters” but got the “number of bytes”. And the most annoying part: with English text, everything may seem to work “as if correctly”, but with Russian it suddenly breaks. The classic: “it worked on my laptop”.
Let us put this into a small table — like a cheat sheet for reading code:
| Operation | What it returns | What it means | Result type |
|---|---|---|---|
|
string length | bytes, not runes | |
|
element by index | one byte | |
|
index and value | index of the byte, value of the rune | |
A small demo (the important thing is to see that i in range is a byte index, not a “character number”):
package main
import "fmt"
func main() {
s := "coffee"
for i, r := range s {
fmt.Printf("i=%d r=%c\n", i, r)
// i=0 r=k
// i=2 r=o
// i=4 r=f
// i=6 r=e
}
}
Why are the indices 0,2,4,6? Because Cyrillic letters in UTF-8 usually take 2 bytes.
byte and rune: “character” is not a byte
When you see the word “character”, it is tempting to think it means something small and fixed. In ASCII, that was true: 1 character = 1 byte. UTF-8 does not guarantee such equality: one character may take 1, 2, 3, or 4 bytes. That is why Go has two frequently used building blocks:
byte is one byte (0..255).
rune is a number (essentially int32) representing a Unicode code point.
Important: a “rune” is not always what the user perceives as “one character on the screen”. Some “human characters” may consist of several code points (for example, a letter + a diacritic). We will not dive into Unicode combining sequences in this lecture, but we should be honest: “one character as seen by the user” is a more complex notion than rune. Our practical goal is simpler: do not break UTF-8 and normalize input correctly.
Conversions you will meet most often:
- []byte(s) — get the string bytes (for low-level work, for example);
- []rune(s) — get runes when you need indexing “by characters” rather than “by bytes”;
- string(runes) — build the string back.
Small example of “carefully taking the first rune”:
package main
import "fmt"
func main() {
s := "coffee"
rs := []rune(s)
fmt.Printf("%c\n", rs[0]) // k
}
This does not mean you should always do it this way. But it is the correct way if you really need the “first rune”, not the “first byte”.
2. Input normalization: spaces and case
Why normalize data at the boundary
Normalization is not “oh, just spaces”. It is a way to turn an unpredictable external world into predictable data inside the program. Ideally, business logic should work like this: “I received a string already in normal form, and from here on I do not need to sprinkle hacks like TrimSpace and ToLower throughout the code”.
Imagine you are writing a small task app (a hypothetical TaskBox). The user enters:
- add Buy milk
- ADD buy milk
- add buy milk
- Add BUY MILK
If you store the task exactly as entered, search, comparison, deduplication, and filters all become more complicated. If you store the task in normalized form, everything becomes straightforward. And here comes an important engineering rule: normalize at the boundary, that is, immediately when reading/creating the value, not “somewhere later”.
A typical simple normalization chain looks like this:
flowchart LR
A[raw input] --> B[TrimSpace]
B --> C[Fields]
C --> D[Join with one space]
D --> E[ToLower or EqualFold in comparisons]
E --> F[valid value inside the program]
TrimSpace, Fields, Join: the basic anti-space toolkit
When it comes to “dirty input”, spaces, tabs, and line breaks are usually to blame. And here Go gives a very pleasant minimal set of functions from strings that solves 80% of real tasks without turning the code into a tragedy.
Important observations:
strings.TrimSpace(s) removes whitespace characters at the ends.
strings.Fields(s) splits by any whitespace characters and does not return empty tokens.
strings.Join(parts, " ") joins them back with a single space.
Together, this gives the effect of “collapsing spaces”: no matter how many spaces there were, inside there will be exactly one.
Here is a small “reference” task title normalizer:
package main
import (
"fmt"
"strings"
)
func normalizeTitle(s string) string {
parts := strings.Fields(strings.TrimSpace(s))
return strings.Join(parts, " ")
}
func main() {
fmt.Println(normalizeTitle(" buy milk ")) // buy milk
}
Note: Fields essentially already includes the idea “it does not matter how many spaces and tabs there are”. That is why strings.Split(s, " ") is usually worse for such tasks: it creates empty elements, and then you have to filter them out.
Case: ToLower and EqualFold
With case, there are two common situations: either you want to normalize and store the data, or you want to compare without regard to case without changing anything.
For “normalize and store”, people usually use strings.ToLower. For “compare without regard to case”, strings.EqualFold is often better, because it does a Unicode-aware comparison (as far as possible without full localization). We will not discuss language subtleties like Turkish I, but it is important to understand the idea: “just convert both strings to lower-case and compare” is often enough, but not always ideal.
In our educational TaskBox, commands may be in any case: ADD, Add, add. So it is convenient to normalize the command to lower-case.
package main
import (
"fmt"
"strings"
)
func normalizeCmd(s string) string {
return strings.ToLower(strings.TrimSpace(s))
}
func main() {
fmt.Println(normalizeCmd(" ADD ")) // add
}
And comparison “are two strings equal regardless of case” is more convenient to express like this:
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.EqualFold("coffee", "COFFEE")) // true
}
3. Command parsing and search
Parsing a user command with Fields
Now let us assemble this into a small part of our application. We will imagine that we have a command string (we received it somehow), and we want to parse:
- an empty string — that is an error;
- the first word — the command;
- everything else — the arguments.
The idea is simple: Fields gives us tokens already without emptiness and without “extra spaces”.
package main
import (
"errors"
"strings"
)
func parseLine(line string) (string, []string, error) {
parts := strings.Fields(strings.TrimSpace(line))
if len(parts) == 0 {
return "", nil, errors.New("empty command")
}
cmd := strings.ToLower(parts[0])
return cmd, parts[1:], nil
}
What matters here is the linear flow: normalization → emptiness check → command extraction. We do not build an else ladder; we immediately return an error if the input is empty.
You can test it on a couple of strings:
package main
import "fmt"
func main() {
cmd, args, err := parseLine(" Add buy milk ")
fmt.Println(cmd, args, err) // add [buy milk] <nil>
}
See how convenient that is? Even if a person entered something “crooked”, we still got a clean structure.
Task title normalization: why Fields+Join is better than TrimSpace
If you do TrimSpace, you only tidy up the edges. But what about the fact that there may be “three spaces in a row” inside? Then you start printing a task list — and it looks as if the user types with their elbows. In search logic, this also gets in the way: the query "buy milk" and the text "buy milk" become “different strings”, although it is obvious to a human that it is the same thing.
That is why it is convenient to store a task title in a “collapsed” form. Let us write a function that returns either a normalized title or an error if it is empty:
package main
import (
"errors"
"strings"
)
func newTitle(raw string) (string, error) {
parts := strings.Fields(strings.TrimSpace(raw))
if len(parts) == 0 {
return "", errors.New("title is empty")
}
return strings.Join(parts, " "), nil
}
And a small check:
package main
import "fmt"
func main() {
t, err := newTitle(" ")
fmt.Printf("%q %v\n", t, err) // "" title is empty
}
Searching within a string: Contains without surprises
When you do substring search, you almost always want to “ignore case”. The user writes milk, but the task is stored as Buy milk. If you compare as-is, there will be no match. So we usually normalize both sides.
The simplest option: convert both strings to lower-case and use strings.Contains. This is not perfect Unicode linguistics, but for educational tasks and most practical scenarios it is quite enough.
package main
import (
"strings"
)
func containsIgnoreCase(s, sub string) bool {
s = strings.ToLower(s)
sub = strings.ToLower(sub)
return strings.Contains(s, sub)
}
If you want to demonstrate it with an example:
package main
import "fmt"
func main() {
fmt.Println(containsIgnoreCase("Buy milk", "MILK")) // true
}
Notice: if you store titles in normalized form in advance (for example, with “collapsed spaces”), then search also becomes more stable with respect to spaces. That is a nice bonus of normalization: it helps not only to “print nicely”, but also to “search consistently”.
4. Practical string work: building and debugging
String building: why strings.Builder is not “optimization for optimization’s sake”
When you assemble a string from pieces, a beginner’s hand reaches for +=. And that is normal: it works, after all! But inside a loop, += often leads to many intermediate strings being created, and the build becomes noticeably heavier, both in time and memory. Sometimes that does not matter. Sometimes it does. And sometimes it matters simply because code with Builder is more honest: “I am building a string”.
For our TaskBox, imagine we want to produce a nice task output as one line: number, status, and title. Builder looks neat here:
package main
import (
"fmt"
"strings"
)
func formatTask(i int, done bool, title string) string {
var b strings.Builder
b.WriteString(fmt.Sprintf("%d) ", i))
if done {
b.WriteString("[x] ")
} else {
b.WriteString("[ ] ")
}
b.WriteString(title)
return b.String()
}
And an example:
package main
import "fmt"
func main() {
fmt.Println(formatTask(1, false, "buy milk")) // 1) [ ] buy milk
}
Yes, there is Sprintf here, which itself creates a string, but the idea of Builder is still clear. At this stage, readability and the pattern itself matter more to us than microscopic optimization.
String diagnostics: printing with %q
String bugs are often invisible. That is, literally invisible: there may be a trailing space in the string, and you cannot see it with your eyes. Or there may be \n, or a tab, or a non-breaking space. That is why a very useful habit is: when debugging strings, print them as a “string literal”, that is, with %q.
This turns “silent” spaces and control characters into visible \n, \t, and so on.
package main
import "fmt"
func main() {
s := " milk \n"
fmt.Printf("%q\n", s) // " milk \n"
}
If you normalize input, then %q is an excellent way to make sure the normalization really removed what you thought it did.
Micro reminder about string constants
In Go there is a subtle but useful detail: a string literal can be an “untyped constant” until the context forces it to become string. In practice, for a beginner it is usually enough to remember that const x = "hello" behaves a bit more freely than a variable, and the compiler may allow assignments/comparisons in a broader context.
Why do we bring this up precisely in a lecture about strings and normalization? Because normalization often leads to creating small “reference values”: for example, commands "add", "list", "done". And it is convenient to keep them as constants: they do not change, and the code becomes more readable.
5. Common mistakes when working with strings and normalization
Mistake #1: treating len(s) as the number of characters.
This is one of the most common traps, because for English strings len and the “number of letters” often match. But as soon as Cyrillic or emoji appears, len starts counting bytes, and the logic of “cut the first N characters” breaks. If you need to count runes, use for range or []rune.
Mistake #2: doing s[i] and thinking it is a “character”.
String indexing returns a byte. If you then print it as %c, you may get gibberish or a fragment of a UTF-8 sequence. For “characters”, use range or []rune, and leave s[i] for cases where you deliberately work with bytes (for example, ASCII or a protocol).
Mistake #3: using strings.Split(s, " ") for user input.
If you have multiple spaces in a row, Split will create empty tokens, and then your code starts living in a world of “filter empty elements”. For “split by whitespace characters”, strings.Fields is usually the right choice: it immediately throws away empties and works with tabs and line breaks too.
Mistake #4: normalize data “somewhere later” instead of at the boundary.
When TrimSpace and ToLower are scattered across the code, you are guaranteed to forget normalization in some new place. Then bugs begin: “why does the command ADD not work”, “why does search sometimes not find”, “why are identical tasks duplicated”. Much more reliable: normalize once when reading/creating the value — and then work only with the normalized form.
Mistake #5: debugging strings without %q.
When a trailing space or an unexpected \n is hiding in a string, ordinary fmt.Println(s) shows you a “pretty picture” but hides the problem. Printing with %q makes the input visible and often saves hours. In programming, this is called “turning on the light and stopping tripping over the furniture”.
GO TO FULL VERSION