Go 字串處理

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

函數: 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.