字符串查找
func Index(s, sep string) int
子串sep在字符串s中第一次出现的位置,不存在则返回-1。
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
}
运行结果:
4
-1
func TrimPrefix(s, prefix string) string
返回去除s可能的前缀prefix的字符串。
package main
import (
"fmt"
"strings"
)
func main() {
var s = "Goodbye,, world!"
s = strings.TrimPrefix(s, "Goodbye,")
s = strings.TrimPrefix(s, "Howdy,")
fmt.Print("Hello" + s)
}
运行结果:
Hello, world!
字符串分割
func Split(s, sep string) []string
用去掉s中出现的sep的方式进行分割,会分割到结尾,并返回生成的所有片段组成的切片
(每一个sep都会进行一次切割,即使两个sep相邻,也会进行两次切割)。
如果sep为空字符,Split会将s切分成每一个unicode码值一个字符串。
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Printf("%q\n", strings.Split("a,b,c", ","))
fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
fmt.Printf("%q\n", strings.Split(" xyz ", ""))
fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
}
运行结果:
["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]
字符串连接
func Join(a []string, sep string) string
将一系列字符串连接为一个字符串,之间用sep来分隔。
下面是将字符串用逗号空格连接起来。
package main
import (
"fmt"
"strings"
)
func main() {
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
}
运行结果: foo, bar, baz
字符串替换
func Replace(s, old, new string, n int) string
返回将s中前n个不重叠old子串都替换为new的新字符串,如果n<0会替换所有old子串。
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
fmt.Println(strings.Replace("knnn kknn kkkn", "k", "ky", 2))
fmt.Println(strings.Replace("knnn kknn kkkn", "kk", "ky", 2))
fmt.Println(strings.Replace("knnn kknn kkkn", "kkk", "ky", 2))
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
}
运行结果:
oinky oinky oink
kynnn kyknn kkkn
knnn kynn kykn
knnn kknn kyn
moo moo moo