清華尹成帶你實戰GO案例(3)Go 字串操作函式

尹成發表於2018-05-21
Go 字串操作函式
strings 標準庫提供了很多字串操作相關的函式。這裡提供的幾個例子是讓你先對這個包有個基本瞭解。
package main
import s "strings"
import "fmt"
// 這裡給fmt.Println起個別名,因為下面我們會多處使用。
var p = fmt.Println
func main() {
// 下面是strings包裡面提供的一些函式例項。注意這裡的函式並不是
// string物件所擁有的方法,這就是說使用這些字串操作函式的時候
// 你必須將字串物件作為第一個引數傳遞進去。
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"))
p()
// 你可以在strings包裡面找到更多的函式
// 這裡還有兩個字串操作方法,它們雖然不是strings包裡面的函式,
// 但是還是值得提一下。一個是獲取字串長度,另外一個是從字串中
// 獲取指定索引的字元
p("Len: ", len("hello"))
p("Char:", "hello"[1])
}


執行結果

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
Len: 5

Char: 101


網址:http://www.qukuailianxueyuan.io/



欲領取造幣技術與全套虛擬機器資料

區塊鏈技術交流QQ群:756146052  備註:CSDN

尹成學院微信:備註:CSDN



相關文章