How to Count Characters in a String in Go

Created
Modified

Using RuneCountInString Function

Straight forward natively use the utf8.RuneCountInString()

The following example should cover whatever you are trying to do:

package main

import (
  "fmt"
  "unicode/utf8"
)

func main() {
  s := "Hello,世界"

  i := utf8.RuneCountInString(s)
  fmt.Println(i)
}
8

Using strings.Count Function

The strings.Count() function counts the number of non-overlapping instances of substr in s. If substr is an empty string, Count returns 1 + the number of Unicode code points in s. For example,

package main

import (
  "fmt"
  "strings"
)

func main() {
  s := "Hello,世界"

  i := strings.Count(s, "l")
  fmt.Println(i)

  // 1 + number
  i = strings.Count(s, "")
  fmt.Printf("points: %d\n", i)

  fmt.Printf("length: %d\n", len(s))
}
2
points: 9
length: 12

Related Tags