目录
1. 官方包
是的,strings.Split 是 Go 语言标准库 strings 包中的函数,属于官方提供的核心功能
2. 支持版本
strings.Split 自 Go 1.0 版本就已存在,所有 Go 1.x 版本均支持,兼容性极强
3. 官方说明
func Split
func Split(s, sep string) []string
英文说明:
Split slices s into all substrings separated by sep and returns a slice of the substrings between those separators.
If s does not contain sep and sep is not empty, Split returns a slice of length 1 whose only element is s.
If sep is empty, Split splits after each UTF-8 sequence. If both s and sep are empty, Split returns an empty slice.
It is equivalent to SplitN with a count of -1.
To split around the first instance of a separator, see Cut.
中文翻译:
将切片拆分为所有以sep分隔的子字符串,并返回分隔符之间的子字符串切片。
如果s不包含sep且sep不为空,Split返回一个长度为1的切片,其中唯一的元素是s。
如果sep为空,Split在每个UTF-8序列之后进行分割。如果s和sep都为空,Split返回一个空片。
它相当于计数为-1的SplitN。
要围绕分隔符的第一个实例进行拆分,请参见切割。
4. 作用
将字符串 s 按照分隔符 sep 分割成子字符串切片。若 sep 为空字符串,则将原字符串按 UTF-8 字符分割。
特点:
- 返回 []string 类型切片
- 空分隔符会按字符分割
- 连续分隔符会产生空字符串元素
5. 实现原理
- 空分隔符处理
- 调用 utf8.DecodeRuneInString 逐个字符分割
- 普通分隔符处理
- 使用 strings.Index 查找分隔符位置
- 预分配切片容量(通过分隔符计数)
- 批量提取子字符串
6. 推荐使用场景和不推荐使用场景
推荐场景
- 解析简单分割数据(如 CSV 行)
- 按固定分隔符拆分(如 PATH 变量)
- 快速字符级操作(如密码字符校验)
不推荐场景
- 复杂结构体数据(用 encodeing/csv)
- 需要正则表达式匹配的分割
- 超长字符串(> 1GB)分割

5962

被折叠的 条评论
为什么被折叠?



