14
9

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でマルチバイトが混在した文字列をtruncateする

さらに文字幅で切り落としたい、そんな場合は go-runwidth が使えます。

package main

import (
	"fmt"
	"github.com/mattn/go-runewidth"
	"strings"
)

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

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

	// 半角5文字で切りたい
	fmt.Println(runewidth.Truncate(s, 5, ""))

	// 画面幅(80文字)で切り、途切れるなら ... を付けたい
	fmt.Println(runewidth.Truncate(strings.Repeat("あ", 60), 80, "..."))
}
14
9
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
14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?