I don't know if the title is clearly, i will explain my problem,
I have this piece of code :
package main
import (
"fmt"
)
func main() {
s := "[email protected]"
fields := []string{}
last := 0
for i, r := range s {
if r == '_' || r == '-' {
fmt.Printf("%q\n", fields)
fields = append(fields, s[last:i 1])
last = i 1
}
}
fmt.Printf("%q\n", fields)
}
This code prints this :
["test-" "email-"]
But i don't know how can I put in the same time the last word, "test" in the same array, so that it gives :
["test-" "email-" "test"]
Anyone has idea please ?
Thanks a lot
CodePudding user response:
I'm not entirely sure what the end goal is, but if it is to get a list of fields separated by -
or _
in the username part of an email address, you may want to just use strings.Split and strings.FieldsFunc.
You can just Split
on @
to get the username part, then use FieldsFunc
to get the fields.
package main
import (
"fmt"
"strings"
)
func main() {
s := "[email protected]"
user := strings.Split(s, "@")[0] // get the username part
fields := strings.FieldsFunc(user, func(c rune) bool {
return c == '-' || c == '_'
})
fmt.Println(fields)
}
CodePudding user response:
Your criteria to cut a string is to find a certain char. The last piece does not match this rule except if you use a string like “a-b-c-“
Advice: check if there is something after last and append it after the for-loop