2
3

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.

Golangで指定した幅で文字列を丸める方法

Last updated at Posted at 2016-02-16

Golangで指定した幅で文字列を丸める方法

一定の文字数で文字列を丸めたい場合があります。

そんな場合はこちら

cutString

str = string([]rune(str)[:maxLen])

応用編
一定数で丸めて、語尾に「...」をつけたい場合があると思います。

cutStringData
func main() {
    // strという文字列を100文字で丸めて、語尾に「...」をつけて表示したい場合
    cutStringData(str,100,"...")
}
func cutStringData(str string, maxLen int, cutString string) string {
    if len(strings.Split(str, "")) < maxLen {
        maxLen = len(strings.Split(str, ""))
        cutString = ""
    }
    str = string([]rune(str)[:maxLen]) + cutString
    return str
}

2
3
2

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?