Go Reference ยท strings and strconv
Go strings.Join() function
Reference for Go strings.Join: concatenate a slice of strings with a separator, how it handles empty and single-element slices, and when to use Builder instead.
strings.Join(elems, sep) concatenates the elements of a []string into one string, placing sep between neighbours. It is the inverse of strings.Split() and is the idiomatic way to build comma lists, paths and sentences.
It computes the final size first and allocates once, so it is much faster than adding strings in a loop.
s := strings.Join([]string{"a", "b", "c"}, "-") // "a-b-c"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Join(elems []string, sep string) string
| Name | Description |
|---|---|
elems |
The strings to join. May be nil or empty. |
sep |
Text inserted between consecutive elements. May be empty. |
Returns: the joined string. An empty or nil slice gives ""; a one-element slice gives that element unchanged (no separator).
Edge cases: empty elements are kept, so []string{"", ""} joined with "," is ",". The separator is never added at the start or end. Join does not panic, apart from the improbable case of a result too large for memory.
Usage notes
- Only
[]string. Go has no generic join over other slice types. Convert elements first (as in the second example) withstrconv.Itoa,fmt.Sprintor a small loop. - Don't put a separator on the last element yourself. Loops that append
", "need cleanup afterwards;Joinavoids that. - Joining in a loop with
+=copies the whole string every time, giving quadratic behavior.Joinorstrings.Builderare both linear. - Building file paths: use
path.Joinorfilepath.Join, which also clean duplicate slashes and... - Escaping:
Joindoes not quote or escape. If elements may contain the separator, the result cannot be split back reliably; useencoding/csvor JSON. - Efficiency: one allocation for the result, plus nothing else. Pre-size when you build the
[]stringwithmake([]string, 0, n). - Skipping empties needs a filter first;
Joinkeeps them on purpose.