Golang:strings模块常用的字符串操作函数
文档
- https://pkg.go.dev/strings
常用函数
函数名 | 说明 |
---|---|
ToUpper(s string) string | 转换为大写字母 |
ToLower(s string) string | 转换为小写字母 |
Count(s, sep string) int | 统计字符串出现的次数 |
Contains(s, substr string) bool | 是否包含子串 |
HasPrefix(s, prefix string) bool | 是否以子串开头 |
HasSuffix(s, suffix string) bool | 是否以子串结尾 |
Split(s, sep string) []string | 拆分字符串 |
Join(a []string, sep string) string | 合并字符串 |
ReplaceAll(s, old, new string) string | 字符串替换 |
示例
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello World"
// 转换为大写字母
fmt.Println(strings.ToUpper(str))
// HELLO WORLD
// 转换为小写字母
fmt.Println(strings.ToLower(str))
// hello world
// 统计字符串出现的次数
fmt.Println(strings.Count(str, "o"))
// 2
// 是否包含子串
fmt.Println(strings.Contains(str, "o"))
// true
// 是否以子串开头
fmt.Println(strings.HasPrefix(str, "Hello"))
// true
// 是否以子串结尾
fmt.Println(strings.HasSuffix(str, "Hello"))
// false
// 字符串的长度
fmt.Println(len(str))
// 11
// 拆分字符串
fmt.Printf("%q\n", strings.Split(str, " "))
// ["Hello" "World"]
// 合并字符串
fmt.Println(strings.Join([]string{"Hello", "World"}, ","))
// Hello,World
// 字符串替换
fmt.Println(strings.ReplaceAll(str, " ", "-"))
// Hello-World
}
参考
「每周译Go」介绍 Go 中的 Strings 包