LoginSignup
1
0

More than 3 years have passed since last update.

Swift4 の String.count を Go でやる

Last updated at Posted at 2020-01-24

やりたいこと

家族👨‍👩‍👦‍👦 を3文字として数えたい。

Swift4 の String.count はすごい

内部でGrapheme Clusterなるアルゴリズムを使っていて、それによってUnicode文字列の文字数を正確に計算できているらしい(参考)。

print("家族👨‍👩‍👧‍👦".count) // -> 3

Go の utf8.RuneCountInString では対応できない

👨‍👩‍👧‍👦が7文字として数えられてしまう。

import "unicode/utf8"

func main() {
    print(utf8.RuneCountInString("家族👨‍👩‍👧‍👦")) // -> 9
}

Go でも Swift4 の String.count がやりたい

github.com/rivo/unisegを使うとGrapheme Clusterを利用して文字列を処理できる。
Playgroundでやるとこんな感じになる。

import "github.com/rivo/uniseg"

func main() {
    print(uniseg.GraphemeClusterCount("家族👨‍👩‍👧‍👦")) // -> 3
}
1
0
0

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