Maxim Yefremov
Maxim Yefremov

Reputation: 14185

cut off last rune in UTF string

How to cut off last rune in UTF string? This method is obviously incorrect:

package main

import ("fmt"
 "unicode/utf8")

func main() {
    string := "你好"
    length := utf8.RuneCountInString(string)
    // how to cut off last rune in UTF string? 
    // this method is obviously incorrect:
    withoutLastRune := string[0:length-1]
    fmt.Println(withoutLastRune)
}

Playground

Upvotes: 2

Views: 527

Answers (2)

iant
iant

Reputation: 1239

Using DecodeLastRuneInString is the best answer. I'll just note that if you prize simpler code over run time efficiency, you can do

    s := []rune(str)
    fmt.Println(string(s[:len(s)-1]))

Upvotes: 0

captncraig
captncraig

Reputation: 23118

Almost,

utf8 package has a function to decode the last rune in a string which also returns its length. Cut that number of bytes off the end and you are golden:

str := "你好"
_, lastSize := utf8.DecodeLastRuneInString(str)
withoutLastRune := str[:len(str)-lastSize]
fmt.Println(withoutLastRune)

playground

Upvotes: 4

Related Questions