Introduction
Text is everywhere in programs: names, messages, file contents, web pages. Go has good tools for working with text, but it has one feature that surprises beginners: a Go string is a sequence of bytes, not of letters. For plain English text there is no difference, but as soon as a text contains an accented letter, a symbol or an emoji, the length in bytes and the number of characters are not the same. This lesson explains bytes and runes, and shows the most useful functions of the strings package.
How it works
A string is written in double quotes. It is read-only: you cannot change a letter inside it, you can only make a new string. Text is stored as UTF-8. A simple letter such as a takes one byte, but a letter such as é takes two. So len("héllo") is 6 and not 5, because len counts bytes. Indexing gives a byte too: s[0] is a number, the byte value, not a one-letter string.
A rune is one character (a Unicode code point), written in single quotes: 'a'. To work with characters, convert the string to a slice of runes with []rune(s), whose length is the number of characters. A for range loop over a string does the same job automatically: it gives the position and the rune for each character, so it is the right way to visit characters. string(r) turns a rune back into text.
Slicing works on strings as on slices: s[1:4] takes bytes 1, 2 and 3. Joining uses +, and strings are compared with == and <.
The strings package has the tools you will use most:
strings.ToUpper(s),ToLower(s)change the case.strings.Contains(s, sub),HasPrefix(s, p),HasSuffix(s, p)test the content.strings.Index(s, sub)gives the position of the first match, or -1.strings.Split(s, ",")cuts text at each separator into a slice, andstrings.Join(parts, "-")glues a slice together.strings.Fields(s)splits on any spaces,strings.TrimSpace(s)removes spaces at both ends.strings.Replace(s, old, new, n)replaces the first n matches (use -1 for all) andstrings.Repeat(s, n)repeats text.
None of these change the original: they all return a new string. Joining many pieces with + in a loop is slow for big texts, because each step copies the text. A strings.Builder avoids that: call sb.WriteString(...) for each piece and sb.String() at the end. The strconv package converts between text and numbers: strconv.Itoa(42) gives "42", and strconv.Atoi("42") gives 42 and an error.
Example
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
word := "héllo"
fmt.Println(len(word), len([]rune(word)))
for i, r := range word {
fmt.Print(i, ":", string(r), " ")
}
fmt.Println()
s := "Go is fun"
fmt.Println(strings.ToUpper(s), s)
fmt.Println(strings.Contains(s, "is"), strings.Index(s, "fun"), strings.HasPrefix(s, "Go"))
fmt.Println(strings.Replace(s, " ", "_", -1))
parts := strings.Split("red,green,blue", ",")
fmt.Println(len(parts), parts[1], strings.Join(parts, "-"))
fmt.Println(strings.TrimSpace(" padded ") + "|")
var sb strings.Builder
for i := 1; i <= 5; i++ {
sb.WriteString(strconv.Itoa(i))
sb.WriteString(" ")
}
fmt.Println(sb.String())
}Line by line
len("héllo")is 6 because é takes two bytes, whilelen([]rune(...))is 5 characters.rangeover the string gives each rune with the byte position where it starts, so the position after é jumps by 2.ToUpper,Contains,Index,HasPrefixandReplaceeach return a new value and leave the original string as it was.Splitcuts the CSV line into three parts, andJoinglues them back with a dash.strings.Buildercollects the numbers 1 to 5 piece by piece, andstrconv.Itoaturns each into text.
Expected result
6 5
0:h 1:é 3:l 4:l 5:o
GO IS FUN Go is fun
true 6 true
Go_is_fun
3 green red-green-blue
padded|
1 2 3 4 5
In the real world
Real text is never only English. Names have accents, messages have emoji, and web pages mix many scripts. Go's UTF-8 strings make this work correctly as long as you remember the difference between bytes and runes. Data files are read as lines and split with strings.Split or strings.Fields, and commands typed by a user are cleaned with strings.TrimSpace and strings.ToLower before they are compared.
Common mistakes
- Using len(s) as the number of letters for text that is not plain English.
- Trying to change a letter with
s[0] = 'x'. Strings are read-only. - Expecting ToUpper to change the string itself. You must use its result.
- Mixing up '' and "": single quotes are one rune, double quotes are a string.
- Joining thousands of pieces with + in a loop. Use strings.Builder.
Best practices
- Use
rangeor[]runeto visit characters, andlenonly for byte counts. - Clean input with TrimSpace and ToLower before you compare.
- Build long text with strings.Builder.
Summary
A Go string is a read-only sequence of UTF-8 bytes. len counts bytes, a rune is one character, and range or []rune visit characters. The strings package finds, splits, joins, trims and replaces text and returns new strings, strings.Builder builds long text efficiently, and strconv converts between text and numbers.
Quick check
Key takeaways
- len(s) counts bytes, not characters; use []rune(s) or utf8.RuneCountInString for characters.
- Strings cannot be changed: functions such as ToUpper and Replace return a new string.
- The strings package has what you need to search, split, join and clean text.
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.