strings
Golang 标准库 - strings
strings 包实现了用于操作 UTF-8 编码字符串的简单函数。
主要功能说明:
-
字符串查找:
Contains检查是否包含子串Index返回子串首次出现位置HasPrefix/HasSuffix检查前缀/后缀
-
字符串处理:
ToUpper/ToLower大小写转换Trim/TrimSpace去除空白字符Replace替换子串
-
字符串分割与连接:
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
}