字符前的字符串分割

I'm new to go and have been using split to my advantage. Recently I came across a problem I wanted to split something, and keep the splitting char in my second slice rather than removing it, or leaving it in the first slice as with SplitAfter.

For example the following code:

strings.Split("email@email.com", "@")

returned: ["email", "email.com"]

strings.SplitAfter("email@email.com", "@")

returned: ["email@", "email.com"]

What's the best way to get ["email", "@email.com"]?

Could this work for you?

s := strings.Split("email@email.com", "@")
address, domain := s[0], "@"+s[1]
fmt.Println(address, domain)
// email @email.com

Then combing and creating a string

var buffer bytes.Buffer
buffer.WriteString(address)
buffer.WriteString(domain)
result := buffer.String()
fmt.Println(result)
// email@email.com

Use strings.Index to find the @ and slice to get the two parts:

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.