字符串前的字符串拆分

问题描述 投票:2回答:2

我是新手,一直在使用分裂给我的优势。最近我遇到了一个问题,我想分裂一些东西,并将分裂字符保留在我的第二个切片而不是删除它,或者将它留在第一个切片中,就像SplitAfter一样。

例如,以下代码:

strings.Split("[email protected]", "@")

返回:["email", "email.com"]

strings.SplitAfter("[email protected]", "@")

返回:["email@", "email.com"]

获得["email", "@email.com"]的最佳方法是什么?

string go split substring slice
2个回答
3
投票

使用strings.Index找到@和切片以获得两部分:

var part1, part2 string
if i := strings.Index(s, "@"); i >= 0 {
    part1, part2 = s[:i], s[i:]
} else {
    // handle case with no @
}

Run it on the playground


0
投票

这对你有用吗?

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]
© www.soinside.com 2019 - 2024. All rights reserved.