go语言常见的字符串处理函数

标签:Go语言首次发布:2024-03-11最近修改:2024-06-14

Contains/是否包含子串

  • 函数原型:

    go
    strings.Contains(s, substr string) bool
  • 用法:判断字符串 s 是否包含子串 substr。

  • 示例:

    go
    s := "Hello, world!"result := strings.Contains(s, "world")fmt.Println(result) // 输出: true

Count/计算子串出现的次数

  • 函数原型:

    go
    strings.Count(s, substr string) int
  • 用法:计算字符串 s 中子串 substr 出现的次数。

  • 示例:

    go
    s := "Hello, hello, hello!"count := strings.Count(s, "hello")fmt.Println(count) // 输出: 3

HasPrefix/判断前缀

  • 函数原型:

    go
    strings.HasPrefix(s, prefix string) bool
  • 用法:判断字符串 s 是否以前缀 prefix 开头。

  • 示例:

    go
    s := "Hello, world!"result := strings.HasPrefix(s, "Hello")fmt.Println(result) // 输出: true

HasSuffix/判断后缀

  • 函数原型:

    go
    strings.HasSuffix(s, suffix string) bool
  • 用法:判断字符串 s 是否以后缀 suffix 结尾。

  • 示例:

    go
    s := "Hello, world!"result := strings.HasSuffix(s, "world!")fmt.Println(result) // 输出: true

Index/子串位置

  • 函数原型:

    go
    strings.Index(s, substr string) int
  • 用法:返回子串 substr 在字符串 s 中第一次出现的位置,如果不存在则返回 -1。

  • 示例:

    go
    s := "Hello, world!"index := strings.Index(s, "world")fmt.Println(index) // 输出: 7

LastIndex/子串最后出现的位置

  • 函数原型:

    go
    strings.LastIndex(s, substr string) int
  • 用法:返回子串 substr 在字符串 s 中最后一次出现的位置,如果不存在则返回 -1。

  • 示例:

    go
    s := "Hello, world, hello!"index := strings.LastIndex(s, "hello")fmt.Println(index) // 输出: 14

Replace/前n个旧子串替换为新子串

  • 函数原型:

    go
    strings.Replace(s, old, new string, n int) string
  • 用法:将字符串 s 中的前 n 个 old 子串替换为 new 子串,如果 n 为 -1 则替换所有。

  • 示例:

    go
    s := "Hello, world!"result := strings.Replace(s, "world", "Go", 1)fmt.Println(result) // 输出: "Hello, Go!"

Split/分隔字符串

  • 函数原型:

    go
    strings.Split(s, sep string) []string
  • 用法:以 sep 为分隔符将字符串 s 分割成字符串切片。

  • 示例:

    go
    s := "apple,banana,orange"fruits := strings.Split(s, ",")fmt.Println(fruits) // 输出: ["apple" "banana" "orange"]

TrimSpace/去除首尾的空白字符

  • 函数原型:

    go
    func TrimSpace(s string) string
  • 用法:去除字符串两端的空白字符(包括空格、换行符、制表符等)。它返回一个新的字符串,该字符串两端的空白字符已经被去除。

  • 示例:

    go
    s := "   hello, world   "trimmedS := strings.TrimSpace(s)fmt.Println(trimmedS) // 输出: "hello, world"

Join/字符串拼接

  • 函数原型:

    go
    strings.Join(a []string, sep string) string
  • 用法:将字符串切片 a 中的所有元素通过 sep 连接成一个字符串。

  • 示例:

    go
    fruits := []string{"apple", "banana", "orange"}s := strings.Join(fruits, ", ")fmt.Println(s) // 输出: "apple, banana, orange"

ToLower/转换为小写

  • 函数原型:

    go
    strings.ToLower(s string) string
  • 将字符串 s 中的所有字符转换为小写。

  • 示例:

    go
    s := "Hello, World!"result := strings.ToLower(s)fmt.Println(result) // 输出: "hello, world!"

ToUpper/转换为大写

  • 函数原型:

    go
    strings.ToUpper(s string) string
  • 将字符串 s 中的所有字符转换为大写。

  • 示例:

    go
    s := "Hello, World!"result := strings.ToUpper(s)fmt.Println(result) // 输出: "HELLO, WORLD!"