V
V
Vadim Rublev2020-06-27 01:26:26
go
Vadim Rublev, 2020-06-27 01:26:26

How do len() and RuneCountInString() measure length?

var question = "¿Cómo estás?" // 12 characters in value.
fmt.Println(len(question), "bytes") // 15 bytes
fmt.Println(utf8.RuneCountInString(question), "runes") // 12 runes
The len() function counts bytes. The length on it will be equal to the number of characters only if these characters are Latin in ASCII encoding.
The utf8.RuneCountInString() function counts runes - 1 rune = 1 character. Any characters that are in UTF-8.
Did I understand correctly?

That is, I don’t understand why in runes the length is equal to the number of characters ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
uvelichitel, 2020-06-27
@uvelichitel

Yes

D
Dimonchik, 2020-06-27
@dimonchik2013

what is the question?
if you work with strings - you work with encodings
; if you are so smart that you always know how many which character occupies a byte - work with bytes and len
, not all of them are like that. For not everyone, they introduced rune, giving the number of characters in a string, regardless of the encoding

RuneCountInString(asciiString)
RuneCountInString(utf8String)

will return the same
what is the question?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question