Calculate the length of string (UTF-8) in Go programming language.
Iterate over the UTF-8 string by for or range keyword
to calculate string length.
Run Code on Go Playground
func StringLength(s string) int {
l := 0
for _, runeValue := range s {
runeValue = runeValue
l++
}
return l
}
for loop iteration
Run Code on Go Playground
import "unicode/utf8"
func StringLength(s string) int {
l := 0
for i, w := 0, 0; i < len(s); i += w {
_, width := utf8.DecodeRuneInString(s[i:])
w = width
l++
}
return l
}
Tested on: The Go Playground
References: