strings 包提供了一些用于操作字符串的函数。以下是一些常用的函数及其简单示例:
Contains - 判断字符串是否包含另一个字符串。
str := "Hello, World!"
if strings.Contains(str, "World") {
fmt.Println("String contains 'World'")
}
Count - 返回字符串中子串的数量。
str := "Hello, World!"
count := strings.Count(str, "o")
fmt.Println(count) // 输出 2
HasPrefix 和 HasSuffix - 检查字符串是否以特定前缀或后缀开始。
str := "Hello, World!"
if strings.HasPrefix(str, "Hello") {
fmt.Println("String has prefix 'Hello'")
}
if strings.HasSuffix(str, "World!") {
fmt.Println("String has suffix 'World!'")
}
Index 和 LastIndex - 返回子串的索引,Index 返回第一次出现的索引,LastIndex 返回最后一次出现的索引。
str := "Hello, World!"
index := strings.Index(str, "World")
lastIndex := strings.LastIndex(str, "o")
fmt.Println(index, lastIndex) // 输出 7 8
Join - 将字符串切片连接成一个新字符串,可以指定连接符。
strs := []string{"Hello", "World", "!"}
result := strings.Join(strs, " ")
fmt.Println(result) // 输出 "Hello World !"
Repeat - 重复字符串指定次数。
str := "Hello, "
repeated := strings.Repeat(str, 3)
fmt.Println(repeated) // 输出 "Hello, Hello, Hello, "
Replace - 替换字符串中所有指定的字符。
str := "Hello, World!"
replaced := strings.Replace(str, "World", "Golang", -1)
fmt.Println(replaced) // 输出 "Hello, Golang!"
Split - 将字符串按指定分隔符分割成切片。
str := "Hello, World, !"
splitted := strings.Split(str, ", ")
fmt.Println(splitted) // 输出 ["Hello", "World", "!"]
ToLower 和 ToUpper - 将字符串转换为小写或大写。
str := "Hello, World!"
lower := strings.ToLower(str)
upper := strings.ToUpper(str)
fmt.Println(lower, upper) // 输出 "hello, world!" HELLO, WORLD!
Trim 和 TrimSpace - 去除字符串首尾的空白字符,Trim 可以指定要去除的字符。
str := " Hello, World! "
trimmed := strings.TrimSpace(str)
fmt.Println(trimmed) // 输出 "Hello, World!"
这些函数提供了处理字符串的基本操作,在日常开发中经常使用。