How to get the number of characters (runes) in a Go string, not bytes?
Hi everyone! I just started learning Go and encountered a problem when counting characters in a string. I'm writing a small password validator: I need to check that the password length is at least 8 characters. I wrote this code:\n\n```go\npackage main\n\nimport "fmt"\n\nfunc main() {\n password := "пароль"\n if len(password) < 8 {\n fmt.Println("Password is too short")\n }\n}\n```\n\nBut the program prints "Password is too short", even though the string "пароль" consists of 6 Russian letters, not 8. I expected len() to return 6, but it returns 12 (if I understood correctly). It seems that len() counts bytes, not characters. How do I correctly count the number of characters in a Go string? Do I need to account for Unicode if the string contains Cyrillic or emoji? I would appreciate code examples.\n\nTags: strings, runes,
No answers yet.
Log in to leave an answer