Go 标准包 strings 学习(8)ReplaceAll,Split,SplitAfter
继续
本次学习
ReplaceAll,Split,SplitAfter
https://pkg.go.dev/strings@go1.20.4#ReplaceAll
func ReplaceAll
ReplaceAll returns a copy of the string s with all non-overlapping instances of old replaced by new. If old is empty, it matches at the beginning of the string and after each UTF-8 sequence, yielding up to k+1 replacements for a k-rune string.
ReplaceAll返回字符串s的副本,其中所有不重叠的old实例替换为new。如果old为空,它匹配字符串的开头和每个UTF-8序列之后,为k-rune字符串产生最多k+1个替换。
案例
输出
moo moo moo
理解
没啥好说的,作用和方法名一样用new把s里面的old全替换掉

func Split
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。
要围绕分隔符的第一个实例进行拆分,请参见切割。
案例
输出
["a" "b" "c"]
["" "man " "plan " "canal panama"]
[" " "x" "y" "z" " "]
[""]
理解
将s用sep拆分成切片

func SplitAfter
SplitAfter slices s into all substrings after each instance of sep and returns a slice of those substrings.
If s does not contain sep and sep is not empty, SplitAfter returns a slice of length 1 whose only element is s.
If sep is empty, SplitAfter splits after each UTF-8 sequence. If both s and sep are empty, SplitAfter returns an empty slice.
It is equivalent to SplitAfterN with a count of -1.
SplitAfter在sep的每个实例之后将s切片为所有子字符串,并返回这些子字符串的一个切片。
如果s不包含sep且sep不为空,则SplitAfter返回一个长度为1的切片,其中唯一的元素是s。
如果sep为空,SplitAfter在每个UTF-8序列之后进行分割。如果s和sep都为空,则SplitAfter返回一个空切片。
它相当于计数为-1的SplitAfterN。
案例1
输出1
["a," "b," "c"]
案例2
输出2
["a," "b," "c," "," ""]