Strings 包

Go Strings
创建于:2020年08月12日 更新于:2020年08月12日

判断前缀、后缀

// HasPrefix 判断字符串 str 是否以 prefix 开头:
strings.HasPrefix(str, prefix string) bool

package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "hello world"
    res := strings.HasPrefix(str, "he")
    fmt.Println(res) // true
}
// HasSuffix 判断字符串 str 是否以 suffix 结尾:
strings.HasSuffix(str, suffix string) bool

func main() {
    str := "hello world"
    res := strings.HasSuffix(str, "wo")
    fmt.Println(res) // false
}

判断是否包含字符串

// Contains 判断字符串 str 是否包含 substr:
strings.Contains(str, substr string) bool

func main() {
    str := "hello world"
    res := strings.Contains(str, " ")
    fmt.Println(res) // true
}

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

// Index 返回字符串 s 在字符串 str 中的索引,-1 表示字符串 str 不包含字符串 s:
strings.Index(str, s string) int

func main() {
    str := "hello world"
    res := strings.Index(str, "o")
    fmt.Println(res) // 4
}
// LastIndex 返回字符串 s 在字符串 str 中最后出现位置的索引,-1 表示字符串 str 不包含字符串 s:
strings.LastIndex(s, str string) int

func main() {
    str := "hello world"
    res := strings.LastIndex(str, "o")
    fmt.Println(res) // 7
}

字符串替换

Replace 用于将字符串 str 中的前 n 个字符串 old 替换为字符串 new,并返回一个新的字符串,如果 n = -1 则替换所有字符串 old 为字符串 new:
strings.Replace(str, old, new, n) string

func main() {
    str := "hello world"
    res := strings.Replace(str, " ", "-", 1)
    fmt.Println(res) // hello-world
}

统计字符串出现次数

//Count 用于计算字符串 s 在字符串 str 中出现的非重叠次数:
strings.Count(str, s string) int

func main() {
    str := "hello world"
    res := strings.Count(str, "o")
    fmt.Println(res) // 2
}

重复字符串

// Repeat 用于重复 count 次字符串 str 并返回一个新的字符串:
strings.Repeat(s, count int) string

func main() {
    str := "hello world"
    res := strings.Repeat(str, 2)
    fmt.Println(res) // hello worldhello world
}

修改字符串大小写

// ToLower 将字符串中的 Unicode 字符全部转换为相应的小写字符:
strings.ToLower(str) string

func main() {
    str := "Hello WORLD"
    res := strings.ToLower(str)
    fmt.Println(res) // hello world
}

// ToUpper 将字符串中的 Unicode 字符全部转换为相应的大写字符:
strings.ToUpper(str) string

func main() {
    str := "Hello world"
    res := strings.ToUpper(str)
    fmt.Println(res) // HELLO WORLD
}

修剪字符串

// 你可以使用 strings.TrimSpace(str) 来剔除字符串开头和结尾的空白符号;如果你想要剔除指定字符,则可以使用 strings.Trim(str, "cut") 来将开头和结尾的 cut 去除掉。该函数的第二个参数可以包含任何字符,如果你只想剔除开头或者结尾的字符串,则可以使用 TrimLeft 或者 TrimRight 来实现。区分大小写

func main() {
    str := "Hello world"
    res := strings.Trim(str, "He")
    fmt.Println(res) // llo world
}

分割字符串

// strings.Fields(str) 利用空白作为分隔符将字符串分割为若干块,并返回一个 slice 。如果字符串只包含空白符号,返回一个长度为 0 的 slice 。



// strings.Split(str, sep) 自定义分割符号 sep 对字符串分割,返回 slice 。

拼接 slice 到字符串

// Join 用于将元素类型为 string 的 slice 使用分割符号来拼接组成一个字符串:
strings.Join(sl []string, sep string) string

func main() {
    str := "H-e-l-l-o world"
    s2 := strings.Split(str, "-")
    res := strings.Join(s2, "|")
    fmt.Printf("%q", res) // "H|e|l|l|o world"
}