Golang : Count number of runes in string
This just a note for myself and perhaps it can be useful to you as well.
To count a length(size) of a string, typically a programmer will just settle for the the builtin.Len() function. However, when dealing with strings with utf8 characters. Please use the utf8.RuneCountInString() function. See the code below to know why :
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str := "abc"
fmt.Printf("Length %s with len() is %d\n", str, len(str)) // correct
unicodeStr := "fuß"
fmt.Printf("Length %s with len() is %d\n", unicodeStr, len(unicodeStr)) // incorrect
fmt.Printf("Length %s with utf8.RuneCountInString() is %d\n", unicodeStr, utf8.RuneCountInString(unicodeStr)) // correct
unicodeStr2 := "你好"
fmt.Printf("Length %s with len() is %d\n", unicodeStr2, len(unicodeStr2)) // incorrect
fmt.Printf("Length %s with utf8.RuneCountInString() is %d\n", unicodeStr2, utf8.RuneCountInString(unicodeStr2)) // correct
}
Output :
Length abc with len() is 3
Length fuß with len() is 4
Length fuß with utf8.RuneCountInString() is 3
Length 你好 with len() is 6
Length 你好 with utf8.RuneCountInString() is 2
See also : Golang : convert rune to integer value
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+36k Upload multiple files with Go
+13.2k Golang : Chunk split or divide a string into smaller chunk example
+10.4k CodeIgniter : How to check if a session exist in PHP?
+11.3k Golang : convert(cast) string to integer value
+11k Golang : Get remaining text such as id or filename after last segment in URL path
+3.3k Detect if Google Analytics and Developer Media are loaded properly or not
+8.1k Golang : Handle sub domain with Gin
+15.9k Golang : Capture stdout of a child process and act according to the result
+6.3k Golang : Array mapping with Interface
+5.1k Facebook : How to force facebook to scrape latest URL link data?
+24.1k Golang : Get current file path of a file or executable
+16k Golang : Get input from keyboard