go言語 文字列に使用されている文字数を取得する

  • 作成日 2021.01.16
  • 更新日 2022.11.04
  • go
go言語 文字列に使用されている文字数を取得する

go言語で、unicode/utf8パッケージのRuneCountInStringを使用して、文字列に使用されている文字数を取得するサンプルコードを記述してます。go言語のバージョンは1.15.4を使用してます。

環境

  • OS windows10 pro 64bit
  • go言語 1.15.4

RuneCountInString使い方

RuneCountInStringを使用すると、文字列に使用されている文字数を取得することが可能です。

utf8.RuneCountInString("文字列")

以下は、utf8.RuneCountInStringを使って、文字列内の文字数を取得するサンプルコードとなります。

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {

	fmt.Println(utf8.RuneCountInString("abcde"))
	// 5

	fmt.Println(utf8.RuneCountInString("あいうえお"))
	// 5

	fmt.Println(utf8.RuneCountInString("令和2年"))
	// 4

	fmt.Println(utf8.RuneCountInString("😁😂😀"))
	// 3

}