Skip to content

Instantly share code, notes, and snippets.

@dsamarin
Created July 10, 2019 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsamarin/e939f7d52fa6d2b17b2f277447bbca47 to your computer and use it in GitHub Desktop.
Save dsamarin/e939f7d52fa6d2b17b2f277447bbca47 to your computer and use it in GitHub Desktop.
// JoinNonEmpty concatenates the elements of a to create a single string. The separator string
// sep is placed between elements in the resulting string, and ignores empty strings.
func JoinNonEmpty(a []string, sep string) string {
switch len(a) {
case 0:
return ""
case 1:
return a[0]
}
n := 0
for i := 0; i < len(a); i++ {
length := len(a[i])
if length == 0 {
continue
}
n += length + len(sep)
}
if n > len(sep) {
n -= len(sep)
}
var b strings.Builder
b.Grow(n)
b.WriteString(a[0])
for _, s := range a[1:] {
if s == "" {
continue
}
b.WriteString(sep)
b.WriteString(s)
}
return b.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment