Created
July 10, 2019 21:26
-
-
Save dsamarin/e939f7d52fa6d2b17b2f277447bbca47 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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