24
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goでマルチバイトが混在した文字列をtruncateする

Last updated at Posted at 2014-10-22

Goで日本語混じりのstringをそのままtruncateすると[]byteとして切りだされるのでお察しの通りになる。

s := "ああaaああ"

// 5文字目まで切りたい
fmt.Println(s[0:5]) //=> あ��

[]rune[]int32のalias)に変換してから必要なぶんを切り出してstringにキャストすればよい。

s := "ああaaああ"
r := []rune(s)

// 5文字目まで切りたい
fmt.Println(string(r[0:5])) //=> ああaaあ

24
21
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
24
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?