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 Golang : Get RGBA values of each image pixel
+14.7k Golang : Save(pipe) HTTP response into a file
+10k Golang : cannot assign type int to value (type uint8) in range error
+7.6k Swift : Convert (cast) String to Double
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+5.2k Golang : Get S3 or CloudFront object or file information
+32k Golang : Copy directory - including sub-directories and files
+7.5k Golang : Trim everything onward after a word
+8.8k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+8.3k Golang : Another camera capture GUI application with GTK and OpenCV
+25.9k Golang : Convert(cast) string to uint8 type and back to string
+5.7k PHP : Get client IP address