menu arrow_back 湛蓝安全空间 |狂野湛蓝,暴躁每天 chevron_right All_wiki chevron_right the-way-to-go_ZH_CN chevron_right eBook chevron_right 04.7.md
  • home 首页
  • brightness_4 暗黑模式
  • cloud
    xLIYhHS7e34ez7Ma
    cloud
    湛蓝安全
    code
    Github
    04.7.md
    10.31 KB / 2024-07-16 23:14:27
        # 4.7 strings 和 strconv 包
    
    作为一种基本数据结构,每种语言都有一些对于字符串的预定义处理函数。Go 中使用 `strings` 包来完成对字符串的主要操作。
    
    ## 4.7.1 前缀和后缀
    
    `HasPrefix()` 判断字符串 `s` 是否以 `prefix` 开头:
    
    ```go
    strings.HasPrefix(s, prefix string) bool
    ```
    
    `HasSuffix()` 判断字符串 `s` 是否以 `suffix` 结尾:
    
    ```go
    strings.HasSuffix(s, suffix string) bool
    ```
    
    示例 4.13 [presuffix.go](examples/chapter_4/presuffix.go)
    
    ```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 字符串包含关系
    
    `Contains()` 判断字符串 `s` 是否包含 `substr`:
    
    ```go
    strings.Contains(s, substr string) bool
    ```
    
    ## 4.7.3 判断子字符串或字符在父字符串中出现的位置(索引)
    
    `Index()` 返回字符串 `str` 在字符串 `s` 中的索引(`str` 的第一个字符的索引),`-1` 表示字符串 `s` 不包含字符串 `str`:
    
    ```go
    strings.Index(s, str string) int
    ```
    
    `LastIndex()` 返回字符串 `str` 在字符串 `s` 中最后出现位置的索引(`str` 的第一个字符的索引),`-1` 表示字符串 `s` 不包含字符串 `str`:
    
    ```go
    strings.LastIndex(s, str string) int
    ```
    
    如果需要查询非 ASCII 编码的字符在父字符串中的位置,建议使用以下函数来对字符进行定位:
    
    ```go
    strings.IndexRune(s string, r rune) int
    ```
    	注: 原文为 "If ch is a non-ASCII character use strings.IndexRune(s string, ch int) int."
    	该方法在最新版本的 Go 中定义为 func IndexRune(s string, r rune) int
    	实际使用中的第二个参数 rune 可以是 rune 或 int, 例如 strings.IndexRune("chicken", 99) 或 strings.IndexRune("chicken", rune('k'))
    
    示例 4.14 [index_in_string.go](examples/chapter_4/index_in_string.go)
    
    ```go
    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 字符串替换
    
    `Replace()` 用于将字符串 `str` 中的前 `n` 个字符串 `old` 替换为字符串 `new`,并返回一个新的字符串,如果 `n = -1` 则替换所有字符串 `old` 为字符串 `new`:
    
    ```go
    strings.Replace(str, old, new string, n int) string
    ```
    
    ## 4.7.5 统计字符串出现次数
    
    `Count()` 用于计算字符串 `str` 在字符串 `s` 中出现的非重叠次数:
    
    ```go
    strings.Count(s, str string) int
    ```
    
    示例 4.15 [count_substring.go](examples/chapter_4/count_substring.go)
    
    ```go
    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 重复字符串
    
    `Repeat()` 用于重复 `count` 次字符串 `s` 并返回一个新的字符串:
    
    ```go
    strings.Repeat(s, count int) string
    ```
    
    示例 4.16 [repeat_string.go](examples/chapter_4/repeat_string.go)
    
    ```go
    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()` 将字符串中的 Unicode 字符全部转换为相应的小写字符:
    
    ```go
    strings.ToLower(s) string
    ```
    
    `ToUpper()` 将字符串中的 Unicode 字符全部转换为相应的大写字符:
    
    ```go
    strings.ToUpper(s) string
    ```
    
    示例 4.17 [toupper_lower.go](examples/chapter_4/toupper_lower.go)
    
    ```go
    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")` 来将开头和结尾的 `cut` 去除掉。该函数的第二个参数可以包含任何字符,如果你只想剔除开头或者结尾的字符串,则可以使用 `TrimLeft()` 或者 `TrimRight()` 来实现。
    
    ## 4.7.9 分割字符串
    
    `strings.Fields(s)` 将会利用 1 个或多个空白符号来作为动态长度的分隔符将字符串分割成若干小块,并返回一个 slice,如果字符串只包含空白符号,则返回一个长度为 0 的 slice。
    
    `strings.Split(s, sep)` 用于自定义分割符号来对指定字符串进行分割,同样返回 slice。
    
    因为这 2 个函数都会返回 slice,所以习惯使用 for-range 循环来对其进行处理(第 7.3 节)。
    
    ## 4.7.10 拼接 slice 到字符串
    
    `Join()` 用于将元素类型为 string 的 slice 使用分割符号来拼接组成一个字符串:
    
    ```go
    strings.Join(sl []string, sep string) string
    ```
    
    示例 4.18 [strings_splitjoin.go](examples/chapter_4/strings_splitjoin.go)
    
    ```go
    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
    
    其它有关字符串操作的文档请参阅 [官方文档](http://golang.org/pkg/strings/)( **译者注:国内用户可访问 [该页面](http://docs.studygolang.com/pkg/strings/)** )。
    
    ## 4.7.11 从字符串中读取内容
    
    函数 `strings.NewReader(str)` 用于生成一个 `Reader` 并读取字符串中的内容,然后返回指向该 `Reader` 的指针,从其它类型读取内容的函数还有:
    
    - `Read()` 从 `[]byte` 中读取内容。
    - `ReadByte()` 和 `ReadRune()` 从字符串中读取下一个 `byte` 或者 `rune`。
    
    ## 4.7.12 字符串与其它类型的转换
    
    与字符串相关的类型转换都是通过 `strconv` 包实现的。
    
    该包包含了一些变量用于获取程序运行的操作系统平台下 `int` 类型所占的位数,如:`strconv.IntSize`。
    
    任何类型 **`T`** 转换为字符串总是成功的。
    
    针对从数字类型转换到字符串,Go 提供了以下函数:
    
    - `strconv.Itoa(i int) string` 返回数字 `i` 所表示的字符串类型的十进制数。
    - `strconv.FormatFloat(f float64, fmt byte, prec int, bitSize int) string` 将 64 位浮点型的数字转换为字符串,其中 `fmt` 表示格式(其值可以是 `'b'`、`'e'`、`'f'` 或 `'g'`),`prec` 表示精度,`bitSize` 则使用 32 表示 `float32`,用 64 表示 `float64`。
    
    将字符串转换为其它类型 **`tp`** 并不总是可能的,可能会在运行时抛出错误 `parsing "…": invalid argument`。
    
    针对从字符串类型转换为数字类型,Go 提供了以下函数:
    
    - `strconv.Atoi(s string) (i int, err error)` 将字符串转换为 `int` 型。
    - `strconv.ParseFloat(s string, bitSize int) (f float64, err error)` 将字符串转换为 `float64` 型。
    
    利用多返回值的特性,这些函数会返回 2 个值,第 1 个是转换后的结果(如果转换成功),第 2 个是可能出现的错误,因此,我们一般使用以下形式来进行从字符串到其它类型的转换:
    
    	val, err = strconv.Atoi(s)
    
    在下面这个示例中,我们忽略可能出现的转换错误:
    
    示例 4.19 [string_conversion.go](examples/chapter_4/string_conversion.go)
    
    ```go
    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` 语句来对可能出现的错误进行分类处理。
    
    更多有关该包的讨论,请参阅 [官方文档](http://golang.org/pkg/strconv/)( **译者注:国内用户可访问 [该页面](http://docs.studygolang.com/pkg/strconv/)** )。
    
    ## 链接
    
    - [目录](directory.md)
    - 上一节:[字符串](04.6.md)
    - 下一节:[时间和日期](04.8.md)
    
    
    links
    file_download