How to get a substring from a string of runes in golang?

You can get a substring of a UTF-8 string without allocating additional memory (you don't have to convert it to a rune slice):

func substring(s string, start int, end int) string {
    start_str_idx := 0
    i := 0
    for j := range s {
        if i == start {
            start_str_idx = j
        }
        if i == end {
            return s[start_str_idx:j]
        }
        i++
    }
    return s[start_str_idx:]
}

func main() {
    s := "世界 Hello"
    fmt.Println(substring(s, 0, 1)) // 世
    fmt.Println(substring(s, 1, 5)) // 界 He
    fmt.Println(substring(s, 3, 8)) // Hello
}

Just convert it to a slice of runes first, slice, then convert the result back:

string([]rune(str)[:20])

Tags:

Unicode

Go

Rune