Closed
Description
In many projects I've seen code like this:
idx = strings.Index(username, "@")
if idx != -1 {
name = username[:idx]
} else {
name = username
}
idx = strings.LastIndex(address, "@")
if idx != -1 {
host = address[idx+1:]
} else {
host = address
}
I think this operation—getting a prefix or suffix based on
a substring—is common enough to think about adding helpers for them.
So I propose to add functions PrefixUntil
and
SuffixAfter
(names up for debate) to package strings.
Something like:
// PrefixUntil returns the prefix of the string s until the first
// occurrence of the substring substr, excluding the substring itself.
// It returns s if substr was not found.
func PrefixUntil(s, substr string) (prefix string) {
var idx = Index(s, substr)
if idx == -1 {
return s
}
return s[:idx]
}
// SuffixAfter returns the suffix of the string s after the last
// occurrence of the substring substr, excluding the substring itself.
// It returns s if substr was not found.
func SuffixAfter(s, substr string) (suffix string) {
var idx = LastIndex(s, substr)
if idx == -1 {
return s
}
return s[idx+len(substr):]
}
So that the code could be rewritten as:
name = strings.PrefixUntil(username, "@")
host = strings.SuffixAfter(address, "@")