7.6 字符串处理

    下面这些函数来自于strings包,这里介绍一些我平常经常用到的函数,更详细的请参考官方的文档。

    • func Contains(s, substr string) bool

      字符串s中是否包含substr,返回bool值

    • func Join(a []string, sep string) string

      字符串链接,把slice a通过sep链接起来

    1. s := []string{"foo", "bar", "baz"}
    2. fmt.Println(strings.Join(s, ", "))
    3. //Output:foo, bar, baz
    • func Index(s, sep string) int

    1. fmt.Println(strings.Index("chicken", "ken"))
    2. fmt.Println(strings.Index("chicken", "dmr"))
    3. //Output:4
    4. //-1
    • func Repeat(s string, count int) string

      重复s字符串count次,最后返回重复的字符串

    • func Replace(s, old, new string, n int) string

      在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换

    1. fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
    2. //Output:oinky oinky oink
    3. //moo moo moo
    • func Split(s, sep string) []string

      把s字符串按照sep分割,返回slice

    1. fmt.Printf("%q\n", strings.Split("a,b,c", ","))
    2. fmt.Printf("%q\n", strings.Split("a man a plan a canal panama", "a "))
    3. fmt.Printf("%q\n", strings.Split(" xyz ", ""))
    4. fmt.Printf("%q\n", strings.Split("", "Bernardo O'Higgins"))
    5. //Output:["a" "b" "c"]
    6. //["" "man " "plan " "canal panama"]
    7. //[" " "x" "y" "z" " "]
    8. //[""]
    • 在s字符串的头部和尾部去除cutset指定的字符串

    • func Fields(s string) []string

      去除s字符串的空格符,并且按照空格分割返回slice

    1. fmt.Printf("Fields are: %q", strings.Fields(" foo bar baz "))
    2. //Output:Fields are: ["foo" "bar" "baz"]

    字符串转化的函数在strconv中,如下也只是列出一些常用的:

    1. package main
    2. import (
    3. "fmt"
    4. "strconv"
    5. )
    6. func main() {
    7. str := make([]byte, 0, 100)
    8. str = strconv.AppendInt(str, 4567, 10)
    9. str = strconv.AppendBool(str, false)
    10. str = strconv.AppendQuote(str, "abcdefg")
    11. str = strconv.AppendQuoteRune(str, '单')
    12. fmt.Println(string(str))
    13. }
    • Format 系列函数把其他类型的转换为字符串 ```Go

    package main

    import ( “fmt” “strconv” )