Go 字符串中的常用函数

  1. 统计字符串的长度,按字节进行统计: len(str)

  2. 字符串遍历,同时处理中文乱码的问题: r := []rune(str)

  3. 字符串转整数: n, err := strconv.Atoi("12")

  4. 整数转字符串: str = strconv.ltoa(12345)

  5. 字符串转 []byte : var bytes = []byte("hello world")

  6. []byte 转字符串: str := string([]byte("hello world"))

  7. 10 进制转其他进制: str = string.FormatInt(123, 进制)

  8. 查找子串是否在指定的字符串中: string.Contains("seafood", "foo") 该函数返回布尔值以表示是否找到结果

  9. 统计一个字符串有几个指定的子串: strings.Contains("awseesdawee", "e")

  10. 不区分大小写的字符串比较: strings.EqualFold("abc", "Abc")

  11. 返回子串在字符串第一次出现的位置,如果没有则返回 -1 : strings.Index("NLT_abc", "abc")

  12. 返回子串在字符串中最后一次出现的位置,如果没有则返回 -1 : strings.LastIndex("go golang", "go")

  13. 将指定的子串替换成另外一个子串: strings.Replace("go go hello", "go", "golang", 1) 。此处这个参数 1 表示需要替换几个。

  14. 按照指定的某个字符,为分割标识,将一个字符串拆分成字符串数组: strings.Split("hello, world,ok", ",")

  15. 将字符串的字母进行大小写的转换:

    strings.ToLower("Go") // go
    strings.ToUpper("go") // GO
    
  16. 将字符串左右两边的空格去掉: strings.TrimSpace(" saw ")

  17. 将字符串左右两边指定的字符去掉: strings.Trim("! sas! ", "!") ,将左右两边的 ! 和空格去掉

  18. 将字符串左边指定的字符去掉: strings.TrimLeft("! hello!")

  19. 将字符串右边指定的字符去掉: strings.TrimRight("!hello!", "!")

  20. 判断字符串是否以指定的字符串开头: strings.HasPrefix("https://www.ctong.top", "htps://")

  21. 判断字符串是否以指定的字符串结束: strings.HasSuffix("https://www.ctong.top", ".rop")

posted @ 2023-06-13 10:04  CloverYou  阅读(22)  评论(0)    收藏  举报