在线文档  >   Golang练习   >   字符串函数

在Go中,标准库的 strings 包提供了许多有用的字符串相关函数。
这里是一些示例,以使您了解该包的功能。

package main

import (
    "fmt"
    s "strings"
)

// 我们将 fmt.Println 别名为一个更短的名称,因为我们将在下面经常使用它。
var p = fmt.Println

func main() {

    // 这里是 `strings` 包中可用的一些函数示例。
    // 由于这些函数来自包中,而不是字符串对象本身的方法,
    // 我们需要作为函数的第一个参数传递问题字符串。
    // 您可以在 [`strings`](https://pkg.go.dev/strings) 包文档中找到更多函数。

    // 判断字符串 s 是否包含 substr
    p("Contains:  ", s.Contains("test", "es"))

    // 统计字符串 s 中 substr 出现的次数
    p("Count:     ", s.Count("test", "t"))

    // 判断字符串 s 是否以 prefix 开头
    p("HasPrefix: ", s.HasPrefix("test", "te"))

    // 判断字符串 s 是否以 suffix 结尾
    p("HasSuffix: ", s.HasSuffix("test", "st"))

    // 返回字符串 s 中 substr 第一次出现的索引
    p("Index:     ", s.Index("test", "e"))

    // 使用连接符将字符串数组或切片连接成单个字符串
    p("Join:      ", s.Join([]string{"a", "b"}, "-"))

    // 将字符重复 count 次,组成新的字符串
    p("Repeat:    ", s.Repeat("a", 5))

    // 将字符串 s 中所有 old 替换为 new,n < 0 表示替换所有匹配项
    p("Replace:   ", s.Replace("foo", "o", "0", -1))

    // 将字符串 s 中 old 第一次出现的位置替换为 new
    p("Replace:   ", s.Replace("foo", "o", "0", 1))

    // 使用 sep 分割字符串 s,返回字符串数组或切片
    p("Split:     ", s.Split("a-b-c-d-e", "-"))

    // 将字符串 s 转换为小写
    p("ToLower:   ", s.ToLower("TEST"))

    // 将字符串 s 转换为大写
    p("ToUpper:   ", s.ToUpper("test"))
}

运行结果如下:

$ go run string-functions.go
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