wx

关注公众号

strings


Golang 标准库 - strings

strings 包实现了用于操作 UTF-8 编码字符串的简单函数。

主要功能说明:

  1. 字符串查找

    • Contains 检查是否包含子串
    • Index 返回子串首次出现位置
    • HasPrefix/HasSuffix 检查前缀/后缀
  2. 字符串处理

    • ToUpper/ToLower 大小写转换
    • Trim/TrimSpace 去除空白字符
    • Replace 替换子串
  3. 字符串分割与连接

    • Split 按分隔符分割
    • Join 用分隔符连接字符串切片
    • Fields 按空白字符分割

func main() {
	// 1. 字符串查找
	fmt.Println("=== 字符串查找 ===")
	fmt.Println(strings.Contains("hello world", "world")) // true
	fmt.Println(strings.Index("hello world", "o"))        // 4
	fmt.Println(strings.HasPrefix("hello", "he"))         // true
	fmt.Println(strings.HasSuffix("hello", "lo"))         // true

	// 2. 字符串处理
	fmt.Println("\n=== 字符串处理 ===")
	fmt.Println(strings.ToUpper("hello"))           // HELLO
	fmt.Println(strings.ToLower("WORLD"))           // world
	fmt.Println(strings.TrimSpace("  hello  "))     // hello
	fmt.Println(strings.Trim("###hello###", "#"))   // hello
	fmt.Println(strings.Replace("hello world", "o", "0", -1)) // hell0 w0rld

	// 3. 字符串分割与连接
	fmt.Println("\n=== 字符串分割与连接 ===")
	parts := strings.Split("a,b,c", ",")
	fmt.Printf("%#v\n", parts) // []string{"a", "b", "c"}

	joined := strings.Join(parts, "-")
	fmt.Println(joined) // a-b-c

	fields := strings.Fields("  hello   world  ")
	fmt.Printf("%#v\n", fields) // []string{"hello", "world"}

	// 4. 字符串重复与计数
	fmt.Println("\n=== 重复与计数 ===")
	fmt.Println(strings.Repeat("go", 3))      // gogogo
	fmt.Println(strings.Count("hello", "l"))  // 2
}
如有疑问关注公众号给我留言
wx

关注公众号

©2017-2023 鲁ICP备17023316号-1 Powered by Hugo