emahiro/b.log

Drastically Repeat Yourself !!!!

【Golang】部分文字列を抽出する

golangの文字列から特定の位置の文字を取り出したい時に [:] を使えます。

package main

import (
    "fmt"
)

func main() {
    s := "abcdefg"
    fmt.Printf("%+v\n", s[:])
    fmt.Printf("%+v\n", s[1:3])
}

/* output
> abcdefg
> bc
*/

cf. https://play.golang.org/p/Gp0PYKtnZfA

但し、マルチバイト文字の場合は落とし穴があるので注意が必要です。UTF-8の文字数では使えません。

package main

import (
    "fmt"
)

func main() {
    s := "あいうえお"
    fmt.Printf("%+v\n", s[:])
    fmt.Printf("%+v\n", s[1:3])
}
/* output
> あいうえお
> ��
*/

cf. https://play.golang.org/p/fToYo08XtaD

UTF-8の文字列で部分文字列を抽出するについては以下のような utf8string をパッケージを使うと良いらしいです。

qiita.com