Skip to content

Go: How to Get the Length of a String With Non-regular Characters

If your string contains some non-regular characters (like Chinese or Russian or currency signs) then you can calculate the length of your string using these two ways.

  1. Convert it to a slice of rune:
len([]rune(myString))

2. Use the utf8 package:

utf8.RuneCountInString(myString)
package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {

	myString := "£"

	fmt.Println(len(myString)) // this is the problem!

	fmt.Println(len([]rune(myString)))
	fmt.Println(utf8.RuneCountInString(myString))
}
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *