douhan9191
2019-02-01 08:37
浏览 553
已采纳

获得Golang字符串的最后一个X字符哪个更好?

When I have string "hogemogehogemogehogemoge世界世界世界" which code is better to get last rune with avoiding memory allocation?

There are similar question about to get last X character of Golang String.

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

I want to make sure which is prefered if I just want to get last rune, without any additional operation.

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    // which is more better for memory allocation?
    s := "hogemogehogemogehogemoge世界世界世界a"
    getLastRune(s, 3)
    getLastRune2(s, 3)
}

func getLastRune(s string, c int) {
    // DecodeLastRuneInString
    j := len(s)
    for i := 0; i < c && j > 0; i++ {
        _, size := utf8.DecodeLastRuneInString(s[:j])
        j -= size
    }
    lastByRune := s[j:]
    fmt.Println(lastByRune)
}

func getLastRune2(s string, c int) {
    // string -> []rune
    r := []rune(s)
    lastByRune := string(r[len(r)-c:])
    fmt.Println(lastByRune)
}

世界a

世界a

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题