依範例進行: 字串函式

標準函式庫的 strings 套件提供了許多有用的字串相關函式。以下是一些範例,讓您了解此套件。

package main
import (
    "fmt"
    s "strings"
)

我們將 fmt.Println 別名設為較短的名稱,因為我們將在下方大量使用它。

var p = fmt.Println
func main() {

以下是 strings 中可用的函式範例。由於這些是來自套件的函式,而非字串物件本身的方法,因此我們需要將字串作為函式的第一個引數傳遞。您可以在 strings 套件文件找到更多函式。

    p("Contains:  ", s.Contains("test", "es"))
    p("Count:     ", s.Count("test", "t"))
    p("HasPrefix: ", s.HasPrefix("test", "te"))
    p("HasSuffix: ", s.HasSuffix("test", "st"))
    p("Index:     ", s.Index("test", "e"))
    p("Join:      ", s.Join([]string{"a", "b"}, "-"))
    p("Repeat:    ", s.Repeat("a", 5))
    p("Replace:   ", s.Replace("foo", "o", "0", -1))
    p("Replace:   ", s.Replace("foo", "o", "0", 1))
    p("Split:     ", s.Split("a-b-c-d-e", "-"))
    p("ToLower:   ", s.ToLower("TEST"))
    p("ToUpper:   ", s.ToUpper("test"))
}
$ go run string-functions.go
Contains:   true
Count:      2
HasPrefix:  true
HasSuffix:  true
Index:      1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [a b c d e]
ToLower:    test
ToUpper:    TEST

下一個範例: 字串格式化