How to get the last X Characters of a Golang String?

前端 未结 2 1290
猫巷女王i
猫巷女王i 2021-01-31 13:25

If I have the string \"12121211122\" and I want to get the last 3 characters (e.g. \"122\"), is that possible in Go? I\'ve looked in the string package and didn\'t

2条回答
  •  攒了一身酷
    2021-01-31 13:56

    The answer depends on what you mean by "characters". If you mean bytes then:

    s := "12121211122"
    lastByByte := s[len(s)-3:]
    

    If you mean runes in a utf-8 encoded string, then:

    s := "12121211122"
    j := len(s)
    for i := 0; i < 3 && j > 0; i++ {
        _, size := utf8.DecodeLastRuneInString(s[:j])
        j -= size
    }
    lastByRune := s[j:]
    

    You can also convert the string to a []rune and operate on the rune slice, but that allocates memory.

提交回复
热议问题