How to get a substring from a string in Go

Created
Modified

Using the slice syntax

A slice is formed by specifying two indices, a low and high bound, separated by a colon:

// a[low : high]
s := "Hello,世界"

// e
fmt.Println(s[1:2])
fmt.Println(s[1:])
// Hello,世界
fmt.Println(s[:])
e
ello,世界
Hello,世界

Length of the the result is high — low.

Indices cannot be arbitrary numbers

negative numbers aren’t allowed. low ≤ high. high ≤ len(input).

s := "Hello,世界"

// negative numbers aren’t allowed
fmt.Println(s[-1:3])
// invalid argument: index -1 (constant of type int) must not be negative

// 12
fmt.Println(len(s))

// high ≤ len(input)
fmt.Println(s[1:20])
// panic: runtime error: slice bounds out of range [:20] with length 12

Only work with ASCII

Operating on strings alone will only work with ASCII and will count wrong when input is a non-ASCII UTF-8 encoded character, and will probably even corrupt characters since it cuts multibyte chars mid-sequence.

For strings that contain non-ASCII Unicode characters (such as emojis, characters from other languages, e.t.c.), a conversion to a rune slice is required before taking a subslice.

s := "Hello,世界"

// wrong, diamond-like shape
fmt.Println(s[6:7])
// 世
fmt.Println(s[6:9])

runes := []rune(s)
// 世
fmt.Println(string(runes[6:7]))

Related Tags