Accessing Substrings
How do I access parts of a given string?
Go allows you to access parts of a string via the normal indexing primitives you’re accustomed to using with arrays and slices. In particular, it allows you to access mystring[n:m]
. Either n
or m
can be omitted, which implies from the beginning or to the end, respectively. There’s also the primitive len(s)
, which gives you the number of characters in the string.
Here are some examples:
test_index.go
package main
import "fmt"
func main() {
s := "Hello World"
fmt.Println(s[:5]) // the first 5 characters
fmt.Println(s[:len(s)-6]) // the same, but counting back from the end
fmt.Println(s[1:]) // all except the first character
fmt.Println(s[len(s)-5:]) // the last 5 characters
fmt.Println(s[1 : len(s)-1]) // all except the first and last
}
$ go run test_index.go
Hello
Hello
ello World
World
ello Worl
Accessing strings by character, word or token are covered in the Processing a String One Word or Character at a Time recipe.