這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
函數: Join(a []string, sep string) string
說明: 將一個字串切片中的元素以字元 sep 進行分隔然後合并成一個字串並返回
執行個體:
func main() { str := []string{"Hello", "World", "Good"} fmt.Println(strings.Join(str, " "))}
程式輸出 Hello World Good
函數: LastIndex(s, sep string) int
說明: 判斷字元 sep 在字串 s 中最後一次出現的位置,如果成功返回 sep 位置的索引,如果字元 sep 不在字串 s 中則返回 -1
執行個體:
func main() { str := "Hello World" fmt.Println(strings.LastIndex(str, "l"))}
程式輸出 9
函數: Repeat(s string, count int) string
說明: 將 count 個字串 s 合并成一個字串並返回
執行個體:
func main() { str := "Hello " fmt.Println(strings.Repeat(str, 5))}
程式輸出 Hello Hello Hello Hello Hello
函數: Replace(s, old, new string, n int) string
說明: 將字串 s 中出現字元 old 的前 n 個替換成 new字元,並返回替換後的字串,如果要替換全部則 n 為 -1 即可
執行個體:
func main() { str := "hi hi hi are you ok" fmt.Println(strings.Replace(str, "hi", "ok", 3))}
程式輸出 ok ok ok are you ok
函數: Split(s, sep string) []string
說明: 將字串 s 中的字串以字元 sep 為分隔字元拆分成若干個元素的字串切片,並返回字串切片
執行個體:
func main() { str := "one,two,three" for _, v := range strings.Split(str, ",") { fmt.Println(v) }}
程式輸出 one two three
函數: SplitAfter(s, sep string) []string
說明: 將字串 s 中的字串以字元 sep 為分隔字元拆分成若干個字串切片並且保留原字串中的分隔字元號,並返回字串切片
執行個體:
func main() { str := "one,two,three" for _, v := range strings.SplitAfter(str, ",") { fmt.Println(v) }}
程式輸出 one, two, three