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
+18.9k Nginx + FastCGI + Go Setup.
+7.9k Golang : How to get username from email address
+21.5k Golang : Get ASCII code from a key press(cross-platform) example
+4.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+22.4k Golang : Use regular expression to validate domain name
+13.3k Golang : Parsing or breaking down URL
+4.6k Unix/Linux : How to find out the hard disk size?
+4.4k Unix/Linux/MacOSx : How to remove an environment variable ?
+11.3k Golang : Sort and reverse sort a slice of bytes
+19.9k Golang : Encrypt and decrypt data with TripleDES
+6k Golang : How to detect if a sentence ends with a punctuation?
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?