4.7 strings 和 strconv 包
strings

4.7.1 前缀和后缀

HasPrefixsprefix
strings.HasPrefix(s, prefix string) bool
HasSuffixssuffix
strings.HasSuffix(s, suffix string) bool

示例 4.13 presuffix.go

package main

import (
    "fmt"
    "strings"
)

func main() {
    var str string = "This is an example of a string"
    fmt.Printf("T/F? Does the string \"%s\" have prefix %s? ", str, "Th")
    fmt.Printf("%t\n", strings.HasPrefix(str, "Th"))
}

输出:

T/F? Does the string "This is an example of a string" have prefix Th? true
\

4.7.2 字符串包含关系

Containsssubstr
strings.Contains(s, substr string) bool

4.7.3 判断子字符串或字符在父字符串中出现的位置(索引)

Indexstrsstrsstr
strings.Index(s, str string) int
LastIndexstrsstrsstr
strings.LastIndex(s, str string) int
ch
strings.IndexRune(s string, r rune) int
package main

import (
    "fmt"
    "strings"
)

func main() {
    var str string = "Hi, I'm Marc, Hi."

    fmt.Printf("The position of \"Marc\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "Marc"))

    fmt.Printf("The position of the first instance of \"Hi\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "Hi"))
    fmt.Printf("The position of the last instance of \"Hi\" is: ")
    fmt.Printf("%d\n", strings.LastIndex(str, "Hi"))

    fmt.Printf("The position of \"Burger\" is: ")
    fmt.Printf("%d\n", strings.Index(str, "Burger"))
}

输出:

The position of "Marc" is: 8
The position of the first instance of "Hi" is: 0
The position of the last instance of "Hi" is: 14
The position of "Burger" is: -1

4.7.4 字符串替换

Replacestrnoldnewn = -1oldnew
strings.Replace(str, old, new, n) string

4.7.5 统计字符串出现次数

Countstrs
strings.Count(s, str string) int
package main

import (
    "fmt"
    "strings"
)

func main() {
    var str string = "Hello, how is it going, Hugo?"
    var manyG = "gggggggggg"

    fmt.Printf("Number of H's in %s is: ", str)
    fmt.Printf("%d\n", strings.Count(str, "H"))

    fmt.Printf("Number of double g's in %s is: ", manyG)
    fmt.Printf("%d\n", strings.Count(manyG, "gg"))
}

输出:

Number of H's in Hello, how is it going, Hugo? is: 2
Number of double g’s in gggggggggg is: 5

4.7.6 重复字符串

Repeatcounts
strings.Repeat(s, count int) string
package main

import (
    "fmt"
    "strings"
)

func main() {
    var origS string = "Hi there! "
    var newS string

    newS = strings.Repeat(origS, 3)
    fmt.Printf("The new repeated string is: %s\n", newS)
}

输出:

The new repeated string is: Hi there! Hi there! Hi there!

4.7.7 修改字符串大小写

ToLower
strings.ToLower(s) string
ToUpper
strings.ToUpper(s) string
package main

import (
    "fmt"
    "strings"
)

func main() {
    var orig string = "Hey, how are you George?"
    var lower string
    var upper string

    fmt.Printf("The original string is: %s\n", orig)
    lower = strings.ToLower(orig)
    fmt.Printf("The lowercase string is: %s\n", lower)
    upper = strings.ToUpper(orig)
    fmt.Printf("The uppercase string is: %s\n", upper)
}

输出:

The original string is: Hey, how are you George?
The lowercase string is: hey, how are you george?
The uppercase string is: HEY, HOW ARE YOU GEORGE?

4.7.8 修剪字符串

strings.TrimSpace(s)strings.Trim(s, "cut")cutTrimLeftTrimRight

4.7.9 分割字符串

strings.Fields(s)
strings.Split(s, sep)

因为这 2 个函数都会返回 slice,所以习惯使用 for-range 循环来对其进行处理(第 7.3 节)。

4.7.10 拼接 slice 到字符串

Join
strings.Join(sl []string, sep string) string
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "The quick brown fox jumps over the lazy dog"
    sl := strings.Fields(str)
    fmt.Printf("Splitted in slice: %v\n", sl)
    for _, val := range sl {
        fmt.Printf("%s - ", val)
    }
    fmt.Println()
    str2 := "GO1|The ABC of Go|25"
    sl2 := strings.Split(str2, "|")
    fmt.Printf("Splitted in slice: %v\n", sl2)
    for _, val := range sl2 {
        fmt.Printf("%s - ", val)
    }
    fmt.Println()
    str3 := strings.Join(sl2,";")
    fmt.Printf("sl2 joined by ;: %s\n", str3)
}

输出:

Splitted in slice: [The quick brown fox jumps over the lazy dog]
The - quick - brown - fox - jumps - over - the - lazy - dog -
Splitted in slice: [GO1 The ABC of Go 25]
GO1 - The ABC of Go - 25 -
sl2 joined by ;: GO1;The ABC of Go;25

其它有关字符串操作的文档请参阅 官方文档( 译者注:国内用户可访问 该页面 )。

4.7.11 从字符串中读取内容

strings.NewReader(str)ReaderReader
Read()ReadByte()ReadRune()

4.7.12 字符串与其它类型的转换

strconv
strconv.IntSize

任何类型 T 转换为字符串总是成功的。

针对从数字类型转换到字符串,Go 提供了以下函数:

strconv.Itoa(i int) stringstrconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) stringfmt'b''e''f''g'precbitSize
parsing "…": invalid argument

针对从字符串类型转换为数字类型,Go 提供了以下函数:

strconv.Atoi(s string) (i int, err error)strconv.ParseFloat(s string, bitSize int) (f float64, err error)

利用多返回值的特性,这些函数会返回 2 个值,第 1 个是转换后的结果(如果转换成功),第 2 个是可能出现的错误,因此,我们一般使用以下形式来进行从字符串到其它类型的转换:

val, err = strconv.Atoi(s)

在下面这个示例中,我们忽略可能出现的转换错误:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    var orig string = "666"
    var an int
    var newS string

    fmt.Printf("The size of ints is: %d\n", strconv.IntSize)      

    an, _ = strconv.Atoi(orig)
    fmt.Printf("The integer is: %d\n", an) 
    an = an + 5
    newS = strconv.Itoa(an)
    fmt.Printf("The new string is: %s\n", newS)
}

输出:

64 位系统:
The size of ints is: 64
32 位系统:
The size of ints is: 32
The integer is: 666
The new string is: 671

在第 5.1 节,我们将会利用 if 语句来对可能出现的错误进行分类处理。

更多有关该包的讨论,请参阅 官方文档( 译者注:国内用户可访问 该页面 )。

链接