LoginSignup
1
0

More than 1 year has passed since last update.

[Go] RuneCountInStringで文字列の文字数を取得

Posted at

Go にて文字列の文字数を取得したい時に

len の場合

byteで数えるまたは一つの Unicode character1~4bytesが使われるため

英語以外の文字列はうまく文字数を取れないことがあります。

unicode/utf-8 パッケージの RuneCountInString 関数を使えば

文字列の文字数を取得できるようになります。

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	name := "テスト太郎"
	fmt.Println("len:", len(name))
	fmt.Println("RuneCountInString:", utf8.RuneCountInString(name))
}
output
len: 15
RuneCountInString: 5
1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0