Go语言strings包提供字符串处理核心API,包含判断(Contains、HasPrefix、HasSuffix)、查找(Index、LastIndex)、替换(Replace、ReplaceAll、Trim)、分割连接(Split、Join)、大小写转换(ToLower、ToUpper)及重复计数(Repeat、Count)等功能,适用于路径解析、文本处理等场景,函数返回新字符串,保证原串不可变,使用安全高效。

Go语言的
strings
strings
这类函数用于判断字符串是否满足某种条件,返回
bool
strings.Contains(s, substr) 判断字符串
s
substr
strings.Contains("hello", "ell")true
strings.HasPrefix(s, prefix) 检查字符串是否以指定前缀开头。
立即学习“go语言免费学习笔记(深入)”;
例如:strings.HasPrefix("gopher", "go")true
strings.HasSuffix(s, suffix) 检查字符串是否以指定后缀结尾。
例如:strings.HasSuffix("image.png", ".png")true
这些函数在路径处理、文件类型判断、URL匹配等场景中非常实用。
用于查找子串在字符串中的位置。
strings.Index(s, substr) 返回子串在字符串中第一次出现的索引,未找到返回
-1
strings.Index("banana", "na")2
strings.LastIndex(s, substr) 返回最后一次出现的索引。
例如:strings.LastIndex("banana", "na")4
这些函数适合用于解析文本、提取特定位置内容等操作。
用于生成修改后的新字符串。
strings.Replace(s, old, new, n) 将字符串中的
old
new
n
n
-1
strings.Replace("hello world", "l", "x", 2)"hexxo world"
strings.ReplaceAll(s, old, new) 相当于
Replace(s, old, new, -1)
strings.ReplaceAll("go-golang-gofmt", "go", "GO")"GO-GOLANG-GOfmt"
strings.Trim(s, cutset) 去除字符串首尾包含在
cutset
strings.Trim("!!!hello!!!", "!")"hello"
还有
TrimSpace
TrimPrefix
TrimSuffix
字符串与切片之间的转换常用操作。
strings.Split(s, sep) 按分隔符将字符串拆分为字符串切片。
例如:strings.Split("a,b,c", ",")[]string{"a", "b", "c"}strings.SplitN(s, sep, n) 限制最多拆分为
n
n
2
strings.SplitN("name:age:city", ":", 2)[]string{"name", "age:city"}strings.Join(elems, sep) 将字符串切片用指定分隔符合并为一个字符串。
例如:strings.Join([]string{"a", "b", "c"}, "-")"a-b-c"
这些函数在解析CSV、URL参数、命令行参数等结构化文本时非常有用。
用于改变字符串的大小写形式。
strings.ToLower(s) 将所有字符转为小写。
strings.ToUpper(s) 转为大写。
strings.ToTitle(s) 将每个单词首字母大写(注意:简单版本,不处理复杂语言规则)。
例如:strings.ToTitle("welcome to go")"WELCOME TO GO"
常用于统一比较、格式化输出等场景。
strings.Repeat(s, count) 重复字符串
count
strings.Repeat("=", 5)"====="
strings.Count(s, substr) 统计子串在字符串中非重叠出现的次数。
例如:strings.Count("cheese", "e")3
注意:统计是**非重叠**的,例如
strings.Count("aaaa", "aa")2
基本上就这些。掌握
strings
以上就是Golang的strings库常用功能有哪些 详解字符串操作API的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号