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 protected]", "@")
returned: ["email", "email.com"]
strings.SplitAfter("[email protected]", "@")
returned: ["email@", "email.com"]
What's the best way to get ["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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With