Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String splitting before character

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"]?

like image 388
Preston Rodeniser Avatar asked Mar 01 '26 07:03

Preston Rodeniser


1 Answers

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.