Count Characters in String?

Viewed 335

You may mistakenly reach for the len func:

package main

import "fmt"

func main() {
	message := "hello"
	fmt.Println(len(message))
}

On initial glance everything looks ok.

However, this is actually counting the number of bytes in the string. Each character in the message we're printing happens to be 1 byte. We got lucky. Our count doesn't work when the string contains a character that is represented by more than a single byte:

package main

import "fmt"

func main() {
	message := "hellö"
	fmt.Println(len(message))
}

The solution is to convert the string to a slice of rune. A rune is used to distinguish character values from integer values. By using a slice of rune we'll get the actual character count:

package main

import "fmt"

func main() {
	message := "hellö"
	fmt.Println(len([]rune(message)))
}
1 Answers

The count of runes in a string may be obtained with utf8.RuneCountInString. For strings that contain only ASCII characters it has a fast path. It performs no allocations.