[Golang] Remove Last Character of UTF-8 String
Remove last character of UTF-8 string via utf8.DecodeLastRuneInString in Go. The code is modified from official example in unicode/utf8 package [2].
import "unicode/utf8"
func RemoveLastChar(str string) string {
for len(str) > 0 {
_, size := utf8.DecodeLastRuneInString(str)
return str[:len(str)-size]
}
return str
}
If you do not want to import unicode/utf8 package, you can use for keyword to range the string to remove last character. On how to range strings, see [3] for more reference.
Tested on: Ubuntu Linux 20.04, Go 1.12.17.
References:
[1] |
[2] |
[3] | [Golang] Iterate Over UTF-8 Strings (non-ASCII strings) |
[4] | implement Backspace and Enter keys in keypad · siongui/paligo@5423f84 · GitHub |