Runes, bytes and strings in Go
A string is bytes; ranging over it yields runes, and the two differ.
func runes(text string) (int, int, string) {
bytes := len(text)
chars := utf8.RuneCountInString(text)
var offsets []string
for index, char := range text {
offsets = append(offsets, fmt.Sprintf("%d:%c", index, char))
if len(offsets) == 3 {
break
}
}
asRunes := []rune(text)
reversed := make([]rune, len(asRunes))
for i, char := range asRunes {
reversed[len(asRunes)-1-i] = char
}
return bytes, chars, string(reversed) + strings.Join(offsets, ",")
}
How it works
lencounts bytes,utf8.RuneCountInStringcounts characters.- Ranging gives the byte offset and the rune at it.
- Indexing a string gives a byte, not a character.
Keywords and builtins used here
appendbreakforfuncifintlenmakerangereturnrunestringvar
The run, in numbers
- Lines
- 20
- Characters to type
- 450
- Tokens
- 131
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 83 seconds.
Step 2 of 5 in Strings & formatting, step 26 of 30 in Language basics.