Go Strings
A string in Go is an immutable sequence of bytes, usually holding UTF-8 encoded text. You write string literals in two ways:
| Literal | Example | Escapes like \n? |
Can span lines? |
|---|---|---|---|
| Interpreted (double quotes) | "Hello\tworld\n" |
yes | no |
| Raw (back quotes) | `C:\path\file` |
no | yes |
package main
import "fmt"
func main() {
greeting := "Hello,\tGo!"
path := `C:\Users\demo\notes.txt`
poem := `Roses are red,
Gophers are blue.`
fmt.Println(greeting)
fmt.Println(path)
fmt.Println(poem)
}Hello, Go!
C:\Users\demo\notes.txt
Roses are red,
Gophers are blue.
Joining and comparing
Use + to concatenate strings and ==, <, > to compare them (comparison is byte by byte, so it is case-sensitive).
package main
import "fmt"
func main() {
first := "Grace"
last := "Hopper"
full := first + " " + last
full += "!"
fmt.Println(full)
fmt.Println("apple" < "banana", "Go" == "go")
}Grace Hopper!
true false
Length, bytes and runes
len(s) returns the number of bytes, not characters. ASCII letters take one byte each, but characters like é or 世 take two to four bytes in UTF-8. Indexing s[i] returns a single byte. To work with characters, loop with range (which decodes runes) or convert to []rune.
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
word := "café"
fmt.Println(len(word)) // bytes
fmt.Println(utf8.RuneCountInString(word)) // characters
fmt.Println(word[0], string(word[0])) // first byte
for i, r := range word {
fmt.Printf("%d:%c ", i, r)
}
fmt.Println()
runes := []rune(word)
fmt.Println(string(runes[3]))
}5
4
99 c
0:c 1:a 2:f 3:é
é
Notice that range jumped from index 3 straight to the end — é occupies bytes 3 and 4.
Strings are immutable
You cannot change a character inside a string: word[0] = 'C' is a compile error. Build a new string instead, for example by slicing: "C" + word[1:]. Slicing s[a:b] returns the bytes from index a up to (not including) b.
The strings package
The standard library's strings package has dozens of helpers. Here are the ones you will use most:
| Function | Example | Result |
|---|---|---|
strings.ToUpper(s) |
ToUpper("go") |
"GO" |
strings.Contains(s, sub) |
Contains("gopher", "ph") |
true |
strings.HasPrefix(s, p) |
HasPrefix("golang", "go") |
true |
strings.Index(s, sub) |
Index("chicken", "ken") |
4 |
strings.Split(s, sep) |
Split("a,b,c", ",") |
[a b c] |
strings.Join(list, sep) |
Join([]string{"a","b"}, "-") |
"a-b" |
strings.Replace(s, old, new, n) |
ReplaceAll("aaa", "a", "b") |
"bbb" |
strings.TrimSpace(s) |
TrimSpace(" hi ") |
"hi" |
strings.Fields(s) |
Fields(" a b ") |
[a b] |
strings.Repeat(s, n) |
Repeat("ab", 3) |
"ababab" |
package main
import (
"fmt"
"strings"
)
func main() {
line := " red, green, blue "
clean := strings.TrimSpace(line)
colors := strings.Split(clean, ", ")
fmt.Println(len(colors), colors)
fmt.Println(strings.Join(colors, " | "))
fmt.Println(strings.ToUpper(colors[1]))
fmt.Println(strings.Contains(clean, "blue"), strings.Index(clean, "green"))
fmt.Println(strings.ReplaceAll(clean, ", ", "/"))
fmt.Println(strings.Repeat("=", 10))
}3 [red green blue]
red | green | blue
GREEN
true 5
red/green/blue
==========
Numbers and strings: strconv
To convert between numbers and their text form, use the strconv package. string(42) would give you the character *, not "42"!
package main
import (
"fmt"
"strconv"
)
func main() {
s := strconv.Itoa(42) // int to string
fmt.Println(s + "!")
n, err := strconv.Atoi("123") // string to int
fmt.Println(n*2, err)
_, err = strconv.Atoi("12a")
fmt.Println(err)
}42!
246 <nil>
strconv.Atoi: parsing "12a": invalid syntax
Tip: Building a long string in a loop with
+=copies it every time. For many pieces, usestrings.Builder— callb.WriteString(...)repeatedly andb.String()at the end.
Test yourself
What does len("héllo") return?
- 5
- 6
- 4
- It panics
How do you convert the int 7 to the string "7"?
string(7)strconv.Itoa(7)str(7)7.String()
Which literal keeps backslashes as written, without escapes?
"C:\\dir"- A raw string in back quotes
'C:\dir'- There is none