typestar

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

  1. len counts bytes, utf8.RuneCountInString counts characters.
  2. Ranging gives the byte offset and the rune at it.
  3. Indexing a string gives a byte, not a character.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 5 in Strings & formatting, step 26 of 30 in Language basics.

← Previous Next →