我是新手,一直在使用分裂给我的优势。最近我遇到了一个问题,我想分裂一些东西,并将分裂字符保留在我的第二个切片而不是删除它,或者将它留在第一个切片中,就像SplitAfter一样。
例如,以下代码:
strings.Split("[email protected]", "@")
返回:["email", "email.com"]
strings.SplitAfter("[email protected]", "@")
返回:["email@", "email.com"]
获得["email", "@email.com"]
的最佳方法是什么?
使用strings.Index找到@
和切片以获得两部分:
var part1, part2 string
if i := strings.Index(s, "@"); i >= 0 {
part1, part2 = s[:i], s[i:]
} else {
// handle case with no @
}
这对你有用吗?
s := strings.Split("[email protected]", "@")
address, domain := s[0], "@"+s[1]
fmt.Println(address, domain)
// email @email.com
然后梳理并创建一个字符串
var buffer bytes.Buffer
buffer.WriteString(address)
buffer.WriteString(domain)
result := buffer.String()
fmt.Println(result)
// [email protected]