Programming Search⌘K

Taskintro

Join a list of strings

Also called join strings, join with a separator, implode, string join, comma-separated list, Collectors.joining.

Join a list of strings into one string with a separator between each two items, and know how each language handles the empty list, items that are not strings and null items.

Task

Join a list of strings into one string, with a separator between each two items. The function join(items, sep) returns items[0] + sep + items[1] + ... + sep + items[k-1]. There is no separator at the start or the end. A list of one item gives the item itself, and the empty list gives the empty string.

A second function, join_numbers(items, sep), joins a list of 32-bit integers. Some languages join items of any type, and some join only strings, so this is where the languages differ most.

Solutions

Language Strings Items that are not strings
Python sep.join(items) sep.join(map(str, items))
JavaScript, TypeScript items.join(sep) items.map(String).join(sep)
Java String.join(sep, items) Collectors.joining(sep) on a stream of strings
C# string.Join(sep, items) string.Join(sep, items) with an explicit culture
Go strings.Join(items, sep) convert to a []string first
Rust items.join(sep) convert to a Vec<String> first
C a loop with memcpy snprintf for each item, then the join
C++ a loop with += std::to_string for each item
Bash a loop with += printf '%d' for each item, then the join
  • Python. join is a method of the separator. It returns "a string which is the concatenation of the strings in iterable", and "A TypeError will be raised if there are any non-string values in iterable"1, so the number function converts each item with str.
  • JavaScript and TypeScript. join "returns a new string that is the concatenation of all elements in this array, separated by commas or a specified separator string"2. It converts each item to a string, so [1, 2].join(",") works. The code calls String on each number to make the conversion clear.
  • Java. String.join takes a separator and an Iterable of CharSequence items. For numbers, the code maps each int to a string and collects with Collectors.joining, which "concatenates the input elements, separated by the specified delimiter"3.
  • C#. string.Join takes a separator and an array or an IEnumerable<T> of any type. For an item that is not a string, "The string representation of each object in the IEnumerable collection is derived by calling that object's ToString method"4. ToString uses the current culture, so the code converts each number with CultureInfo.InvariantCulture.
  • Go. "Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string"5. It takes only a []string, so the code converts each number with strconv.Itoa.
  • Rust. join on a slice "Flattens a slice of T into a single value Self::Output, placing a given separator between each"6. It works on &[&str] and on Vec<String>. For numbers, the code collects the strings into a Vec first.
  • C. The code makes two passes. The first adds up the lengths of the items and the separators, and the second copies each part with memcpy into one allocation. The caller frees the result. join_numbers writes each number with snprintf into a buffer of 12 bytes, which holds -2147483648 and the null byte.
  • C++. C++23 adds std::views::join_with, which flattens a view of ranges "with every element of the delimiter inserted in between elements of the view"7. The code uses a loop, so it works with a library that does not have join_with yet. It adds up the sizes, calls reserve once and appends with +=.
  • Bash. In double quotes, $* joins the arguments "separated by the first character of the IFS variable"8, so it cannot use a separator of two or more characters. The function puts the first item in the result and appends the separator and the next item in a loop.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of join_numbers are in cases/numbers.jsonl.

  • empty-list: the result is the empty string, not the separator.
  • single: one item and no separator.
  • empty-items and empty-middle: an empty item is still an item, so three empty items give two separators, ",,".
  • empty-sep: the join is a concatenation of all the items.
  • long-sep, non-ascii and astral-sep: the separator is any string. A solution that takes only one character, such as IFS in Bash, fails these cases.
  • sep-in-item: ["a,b", "c"] and ["a", "b", "c"] give the same result with a comma. A join loses the boundaries when an item can hold the separator, so a split cannot always undo it. Quote or escape the items, as CSV does, if you must split the result again.
  • int32-ends: the numbers 2147483647 and -2147483648 need 10 and 11 characters.

Pitfalls

  • Python join of a string joins its characters. A str is an iterable of characters, so ",".join("abc") is "a,b,c". None and numbers raise TypeError:
print(",".join("abc"))
print(",".join(["abc"]))
try:
    print(",".join(["a", None]))
except TypeError as e:
    print("TypeError:", e)
print(repr(",".join([])))
Output
a,b,c
abc
TypeError: sequence item 1: expected str instance, NoneType found
''
  • JavaScript joins an array with a comma when it makes a string of it. "The toString method of arrays calls join() internally"9, so a template literal gives Ann,Bo with no space. "If an element is undefined or null, it is converted to an empty string"2:
const names = ["Ann", "Bo"];
console.log(names.join());
console.log(`names: ${names}`);
console.log(String([]) === "");
console.log([null, undefined].join("-"));
Output
Ann,Bo
names: Ann,Bo
true
-
  • Java String.join writes null as text. For a null element, String.join adds the text null10. Collectors.joining with a prefix and a suffix adds them "with the specified prefix and suffix"3, also for an empty stream:
import java.util.List;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args) {
    System.out.println(String.join(",", "a", null, "b"));
    System.out.println(List.of("a", "b").stream().collect(Collectors.joining(", ", "[", "]")));
    System.out.println(List.<String>of().stream().collect(Collectors.joining(", ", "[", "]")));
    System.out.println(List.of(1, 2, 3).stream().map(String::valueOf).collect(Collectors.joining("+")));
  }
}
Output
a,null,b
[a, b]
[]
1+2+3
  • C# string.Join uses the current culture. In the culture de-DE, 1.5 is 1,5, so a join with a comma gives 1,5,2,25, and nobody can split it again. "If any element in value is null, an empty string is used instead"4:
using System.Globalization;

CultureInfo.CurrentCulture = new CultureInfo("de-DE");
double[] prices = { 1.5, 2.25 };
Console.WriteLine(string.Join(",", prices));
Console.WriteLine(string.Join(",", prices.Select(p => p.ToString(CultureInfo.InvariantCulture))));
Console.WriteLine(string.Join("|", new object?[] { 1, null, "x" }));
Output
1,5,2,25
1.5,2.25
1||x
  • A loop that adds the separator after each item. It leaves one separator at the end. strings.Join adds it only between items. fmt.Sprint of a slice gives brackets and spaces, not a join:
package main

import (
	"fmt"
	"strings"
)

func main() {
	items := []string{"a", "b", "c"}
	var s string
	for _, it := range items {
		s += it + ","
	}
	fmt.Printf("%q\n", s)
	fmt.Printf("%q\n", strings.Join(items, ","))
	fmt.Printf("%q\n", strings.Join(nil, ","))
	fmt.Println(fmt.Sprint([]int{1, 2, 3}))
}
Output
"a,b,c,"
"a,b,c"
""
[1 2 3]
  • Rust concat has no separator, and join needs strings. join takes a slice of &str or of String, so convert the numbers first:
fn main() {
    let words = ["red", "green", "blue"];
    println!("{}", words.join(", "));
    println!("{}", words.concat());
    let owned: Vec<String> = words.iter().map(|w| w.to_uppercase()).collect();
    println!("{}", owned.join("-"));
    let nums = [1, 2, 3];
    let parts: Vec<String> = nums.iter().map(|n| n.to_string()).collect();
    println!("{}", parts.join("+"));
}
Output
red, green, blue
redgreenblue
RED-GREEN-BLUE
1+2+3
  • Bash printf with a separator in the format. printf '%s, ' repeats the format for each argument, so it leaves a comma and a space at the end, and ${line%, } removes it. With no arguments, the format runs once, because "the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied"8. So the empty list gives a comma and a space, and not the empty string. IFS=', ' joins with a comma only:
set -- a b c
(IFS=', '; echo "$*")
printf -v line '%s, ' "$@"
echo "[$line]"
echo "[${line%, }]"
set --
printf -v line '%s, ' "$@"
echo "[$line]"
Output
a,b,c
[a, b, c, ]
[a, b, c]
[, ]

Code

The build runs the native tests of each language in a pinned toolchain.

join.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/join-a-list-of-strings/.


def join(items: list[str], sep: str) -> str:
    """Return the items with sep between each two."""
    # join is a method of the separator, and it takes any iterable of str.
    return sep.join(items)


def join_numbers(items: list[int], sep: str) -> str:
    """Return the decimal form of each item, with sep between each two."""
    # join raises TypeError for an item that is not a str, so convert first.
    return sep.join(map(str, items))
test_join.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/join-a-list-of-strings/.

import pytest

from join import join, join_numbers

CASES = {
    "comma": (["a", "b", "c"], ",", "a,b,c"),
    "comma-space": (["red", "green", "blue"], ", ", "red, green, blue"),
    "words": (["Hello", "world"], " ", "Hello world"),
    "empty-list": ([], ",", ""),
    "single": (["only"], ",", "only"),
    "empty-items": (["", "", ""], ",", ",,"),
    "empty-middle": (["a", "", "b"], "-", "a--b"),
    "empty-sep": (["a", "b", "c"], "", "abc"),
    "long-sep": (["x", "y"], " -> ", "x -> y"),
    "non-ascii": (["naïve", "日本"], "·", "naïve·日本"),
    "astral-sep": (["a", "b"], "\U0001f642", "a\U0001f642b"),
    "sep-in-item": (["a,b", "c"], ",", "a,b,c"),
}

NUMBER_CASES = {
    "numbers": ([1, 2, 3], ",", "1,2,3"),
    "negative": ([-1, 0, 1], " ", "-1 0 1"),
    "empty": ([], ",", ""),
    "single": ([42], ",", "42"),
    "int32-ends": ([2147483647, -2147483648], ";", "2147483647;-2147483648"),
}


@pytest.mark.parametrize("name", CASES)
def test_join(name):
    items, sep, want = CASES[name]
    assert join(items, sep) == want


@pytest.mark.parametrize("name", NUMBER_CASES)
def test_join_numbers(name):
    items, sep, want = NUMBER_CASES[name]
    assert join_numbers(items, sep) == want
join.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

#include "join.hpp"

#include <cstddef>

std::string join(std::span<const std::string_view> items, std::string_view sep) {
    // C++23 has std::views::join_with, but the loop also works with a C++20
    // library. It adds up the sizes, reserves once and appends each part.
    std::size_t total = 0;
    for (std::size_t i = 0; i < items.size(); i++) {
        total += items[i].size() + (i > 0 ? sep.size() : 0);
    }
    std::string r;
    r.reserve(total);
    for (std::size_t i = 0; i < items.size(); i++) {
        if (i > 0) {
            r += sep;
        }
        r += items[i];
    }
    return r;
}

std::string join_numbers(std::span<const std::int32_t> items, std::string_view sep) {
    std::string r;
    for (std::size_t i = 0; i < items.size(); i++) {
        if (i > 0) {
            r += sep;
        }
        r += std::to_string(items[i]);
    }
    return r;
}
join.hpp 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

#pragma once

#include <cstdint>
#include <span>
#include <string>
#include <string_view>

// join returns the items with sep between each two.
std::string join(std::span<const std::string_view> items, std::string_view sep);

// join_numbers returns the decimal form of each item, with sep between each two.
std::string join_numbers(std::span<const std::int32_t> items, std::string_view sep);
test_join.cpp 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

#include "join.hpp"

#include <cstdint>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, const std::string &got, std::string_view want) {
    if (got != want) {
        std::cerr << "case " << name << ": got [" << got << "], want [" << want << "]\n";
        failures++;
    }
}

using V = std::vector<std::string_view>;
using N = std::vector<std::int32_t>;

int main() {
    check("comma", join(V{"a", "b", "c"}, ","), "a,b,c");
    check("comma-space", join(V{"red", "green", "blue"}, ", "), "red, green, blue");
    check("words", join(V{"Hello", "world"}, " "), "Hello world");
    check("empty-list", join(V{}, ","), "");
    check("single", join(V{"only"}, ","), "only");
    check("empty-items", join(V{"", "", ""}, ","), ",,");
    check("empty-middle", join(V{"a", "", "b"}, "-"), "a--b");
    check("empty-sep", join(V{"a", "b", "c"}, ""), "abc");
    check("long-sep", join(V{"x", "y"}, " -> "), "x -> y");
    check("non-ascii", join(V{"naïve", "日本"}, "·"), "naïve·日本");
    check("astral-sep", join(V{"a", "b"}, "\U0001F642"), "a\U0001F642b");
    check("sep-in-item", join(V{"a,b", "c"}, ","), "a,b,c");

    check("numbers", join_numbers(N{1, 2, 3}, ","), "1,2,3");
    check("negative", join_numbers(N{-1, 0, 1}, " "), "-1 0 1");
    check("empty", join_numbers(N{}, ","), "");
    check("single-number", join_numbers(N{42}, ","), "42");
    check("int32-ends", join_numbers(N{INT32_MAX, INT32_MIN}, ";"), "2147483647;-2147483648");

    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Join.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/** Joins a list of strings, and a list of numbers, with a separator. */
public final class Join {
  private Join() {}

  /** Returns the items with sep between each two. */
  public static String join(List<String> items, String sep) {
    return String.join(sep, items);
  }

  /** Returns the decimal form of each item, with sep between each two. */
  public static String joinNumbers(int[] items, String sep) {
    // String.join takes only CharSequence items, so the stream converts each
    // int first.
    return Arrays.stream(items).mapToObj(Integer::toString).collect(Collectors.joining(sep));
  }
}
JoinTest.java 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class JoinTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("comma", List.of("a", "b", "c"), ",", "a,b,c"),
        Arguments.of("comma-space", List.of("red", "green", "blue"), ", ", "red, green, blue"),
        Arguments.of("words", List.of("Hello", "world"), " ", "Hello world"),
        Arguments.of("empty-list", List.of(), ",", ""),
        Arguments.of("single", List.of("only"), ",", "only"),
        Arguments.of("empty-items", List.of("", "", ""), ",", ",,"),
        Arguments.of("empty-middle", List.of("a", "", "b"), "-", "a--b"),
        Arguments.of("empty-sep", List.of("a", "b", "c"), "", "abc"),
        Arguments.of("long-sep", List.of("x", "y"), " -> ", "x -> y"),
        Arguments.of("non-ascii", List.of("naïve", "日本"), "·", "naïve·日本"),
        Arguments.of("astral-sep", List.of("a", "b"), "🙂", "a🙂b"),
        Arguments.of("sep-in-item", List.of("a,b", "c"), ",", "a,b,c"));
  }

  static Stream<Arguments> numberCases() {
    return Stream.of(
        Arguments.of("numbers", new int[] {1, 2, 3}, ",", "1,2,3"),
        Arguments.of("negative", new int[] {-1, 0, 1}, " ", "-1 0 1"),
        Arguments.of("empty", new int[] {}, ",", ""),
        Arguments.of("single", new int[] {42}, ",", "42"),
        Arguments.of("int32-ends", new int[] {2147483647, -2147483648}, ";", "2147483647;-2147483648"));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void join(String name, List<String> items, String sep, String want) {
    assertEquals(want, Join.join(items, sep));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("numberCases")
  void joinNumbers(String name, int[] items, String sep, String want) {
    assertEquals(want, Join.joinNumbers(items, sep));
  }
}
join.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

#include "join.h"

#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *join(const char *const *items, size_t n, const char *sep) {
    // The first pass adds up the lengths, so the code allocates once.
    size_t seplen = strlen(sep);
    size_t total = 1;
    for (size_t i = 0; i < n; i++) {
        total += strlen(items[i]) + (i > 0 ? seplen : 0);
    }
    char *r = malloc(total);
    if (r == NULL) {
        return NULL;
    }
    char *p = r;
    for (size_t i = 0; i < n; i++) {
        if (i > 0) {
            memcpy(p, sep, seplen);
            p += seplen;
        }
        size_t len = strlen(items[i]);
        memcpy(p, items[i], len);
        p += len;
    }
    *p = '\0';
    return r;
}

char *join_numbers(const int32_t *items, size_t n, const char *sep) {
    // An int32_t has at most 11 characters, "-2147483648", plus the null byte.
    char (*digits)[12] = malloc((n ? n : 1) * sizeof *digits);
    const char **parts = malloc((n ? n : 1) * sizeof *parts);
    char *r = NULL;
    if (digits != NULL && parts != NULL) {
        for (size_t i = 0; i < n; i++) {
            snprintf(digits[i], sizeof digits[i], "%" PRId32, items[i]);
            parts[i] = digits[i];
        }
        r = join(parts, n, sep);
    }
    free(parts);
    free(digits);
    return r;
}
join.h 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

#ifndef JOIN_H
#define JOIN_H

#include <stddef.h>
#include <stdint.h>

// join returns the n items with sep between each two, in a new string that
// the caller frees. It returns NULL if the allocation fails.
char *join(const char *const *items, size_t n, const char *sep);

// join_numbers returns the decimal form of each of the n items, with sep
// between each two, in a new string that the caller frees.
char *join_numbers(const int32_t *items, size_t n, const char *sep);

#endif
test_join.c 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

#include "join.h"

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN(a) (sizeof(a) / sizeof((a)[0]))

static int failures = 0;

static void check(const char *name, char *got, const char *want) {
    if (got == NULL || strcmp(got, want) != 0) {
        fprintf(stderr, "case %s: got [%s], want [%s]\n", name, got ? got : "NULL", want);
        failures++;
    }
    free(got);
}

int main(void) {
    const char *comma[] = {"a", "b", "c"};
    const char *colors[] = {"red", "green", "blue"};
    const char *words[] = {"Hello", "world"};
    const char *single[] = {"only"};
    const char *empties[] = {"", "", ""};
    const char *middle[] = {"a", "", "b"};
    const char *xy[] = {"x", "y"};
    const char *non_ascii[] = {"na\xc3\xafve", "\xe6\x97\xa5\xe6\x9c\xac"};
    const char *ab[] = {"a", "b"};
    const char *sep_in[] = {"a,b", "c"};

    check("comma", join(comma, LEN(comma), ","), "a,b,c");
    check("comma-space", join(colors, LEN(colors), ", "), "red, green, blue");
    check("words", join(words, LEN(words), " "), "Hello world");
    check("empty-list", join(NULL, 0, ","), "");
    check("single", join(single, LEN(single), ","), "only");
    check("empty-items", join(empties, LEN(empties), ","), ",,");
    check("empty-middle", join(middle, LEN(middle), "-"), "a--b");
    check("empty-sep", join(comma, LEN(comma), ""), "abc");
    check("long-sep", join(xy, LEN(xy), " -> "), "x -> y");
    // U+00B7 MIDDLE DOT is C2 B7 in UTF-8.
    check("non-ascii", join(non_ascii, LEN(non_ascii), "\xc2\xb7"), "na\xc3\xafve\xc2\xb7\xe6\x97\xa5\xe6\x9c\xac");
    // U+1F642 is F0 9F 99 82 in UTF-8.
    check("astral-sep", join(ab, LEN(ab), "\xf0\x9f\x99\x82"), "a\xf0\x9f\x99\x82" "b");
    check("sep-in-item", join(sep_in, LEN(sep_in), ","), "a,b,c");

    const int32_t numbers[] = {1, 2, 3};
    const int32_t negative[] = {-1, 0, 1};
    const int32_t answer[] = {42};
    const int32_t ends[] = {INT32_MAX, INT32_MIN};
    check("numbers", join_numbers(numbers, LEN(numbers), ","), "1,2,3");
    check("negative", join_numbers(negative, LEN(negative), " "), "-1 0 1");
    check("empty", join_numbers(NULL, 0, ","), "");
    check("single-number", join_numbers(answer, LEN(answer), ","), "42");
    check("int32-ends", join_numbers(ends, LEN(ends), ";"), "2147483647;-2147483648");

    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Join.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

using System.Collections.Generic;
using System.Globalization;
using System.Linq;

public static class Join
{
    /// <summary>Returns the items with sep between each two.</summary>
    public static string Strings(IEnumerable<string> items, string sep) =>
        string.Join(sep, items);

    /// <summary>Returns the decimal form of each item, with sep between each two.</summary>
    public static string Numbers(IEnumerable<int> items, string sep) =>
        // string.Join<T> calls ToString with the current culture, so the code
        // converts each item with the invariant culture first.
        string.Join(sep, items.Select(n => n.ToString(CultureInfo.InvariantCulture)));
}
JoinTests.cs 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

using Xunit;

public sealed class JoinTests
{
    public static TheoryData<string, string[], string, string> Cases => new()
    {
        { "comma", new[] { "a", "b", "c" }, ",", "a,b,c" },
        { "comma-space", new[] { "red", "green", "blue" }, ", ", "red, green, blue" },
        { "words", new[] { "Hello", "world" }, " ", "Hello world" },
        { "empty-list", new string[] { }, ",", "" },
        { "single", new[] { "only" }, ",", "only" },
        { "empty-items", new[] { "", "", "" }, ",", ",," },
        { "empty-middle", new[] { "a", "", "b" }, "-", "a--b" },
        { "empty-sep", new[] { "a", "b", "c" }, "", "abc" },
        { "long-sep", new[] { "x", "y" }, " -> ", "x -> y" },
        { "non-ascii", new[] { "naïve", "日本" }, "·", "naïve·日本" },
        { "astral-sep", new[] { "a", "b" }, "\U0001F642", "a\U0001F642b" },
        { "sep-in-item", new[] { "a,b", "c" }, ",", "a,b,c" },
    };

    public static TheoryData<string, int[], string, string> NumberCases => new()
    {
        { "numbers", new[] { 1, 2, 3 }, ",", "1,2,3" },
        { "negative", new[] { -1, 0, 1 }, " ", "-1 0 1" },
        { "empty", new int[] { }, ",", "" },
        { "single", new[] { 42 }, ",", "42" },
        { "int32-ends", new[] { 2147483647, -2147483648 }, ";", "2147483647;-2147483648" },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Strings(string name, string[] items, string sep, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Join.Strings(items, sep));
    }

    [Theory]
    [MemberData(nameof(NumberCases))]
    public void Numbers(string name, int[] items, string sep, string want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Join.Numbers(items, sep));
    }
}
join.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

/**
 * Returns the items with sep between each two.
 * @param {string[]} items
 * @param {string} sep
 * @returns {string}
 */
export function join(items, sep) {
  // join with no argument uses a comma, so the code always passes sep.
  return items.join(sep);
}

/**
 * Returns the decimal form of each item, with sep between each two.
 * @param {number[]} items
 * @param {string} sep
 * @returns {string}
 */
export function joinNumbers(items, sep) {
  return items.map(String).join(sep);
}
join.test.js 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { join, joinNumbers } from "./join.js";

const cases = [
  ["comma", ["a", "b", "c"], ",", "a,b,c"],
  ["comma-space", ["red", "green", "blue"], ", ", "red, green, blue"],
  ["words", ["Hello", "world"], " ", "Hello world"],
  ["empty-list", [], ",", ""],
  ["single", ["only"], ",", "only"],
  ["empty-items", ["", "", ""], ",", ",,"],
  ["empty-middle", ["a", "", "b"], "-", "a--b"],
  ["empty-sep", ["a", "b", "c"], "", "abc"],
  ["long-sep", ["x", "y"], " -> ", "x -> y"],
  ["non-ascii", ["naïve", "日本"], "·", "naïve·日本"],
  ["astral-sep", ["a", "b"], "\u{1F642}", "a\u{1F642}b"],
  ["sep-in-item", ["a,b", "c"], ",", "a,b,c"],
];

const numberCases = [
  ["numbers", [1, 2, 3], ",", "1,2,3"],
  ["negative", [-1, 0, 1], " ", "-1 0 1"],
  ["empty", [], ",", ""],
  ["single", [42], ",", "42"],
  ["int32-ends", [2147483647, -2147483648], ";", "2147483647;-2147483648"],
];

for (const [name, items, sep, want] of cases) {
  test(name, () => {
    assert.equal(join(items, sep), want);
  });
}

for (const [name, items, sep, want] of numberCases) {
  test("numbers " + name, () => {
    assert.equal(joinNumbers(items, sep), want);
  });
}
join.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

/** Returns the items with sep between each two. */
export function join(items: readonly string[], sep: string): string {
  // join with no argument uses a comma, so the code always passes sep.
  return items.join(sep);
}

/** Returns the decimal form of each item, with sep between each two. */
export function joinNumbers(items: readonly number[], sep: string): string {
  return items.map(String).join(sep);
}
join.test.ts 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { join, joinNumbers } from "./join.ts";

const cases: [string, string[], string, string][] = [
  ["comma", ["a", "b", "c"], ",", "a,b,c"],
  ["comma-space", ["red", "green", "blue"], ", ", "red, green, blue"],
  ["words", ["Hello", "world"], " ", "Hello world"],
  ["empty-list", [], ",", ""],
  ["single", ["only"], ",", "only"],
  ["empty-items", ["", "", ""], ",", ",,"],
  ["empty-middle", ["a", "", "b"], "-", "a--b"],
  ["empty-sep", ["a", "b", "c"], "", "abc"],
  ["long-sep", ["x", "y"], " -> ", "x -> y"],
  ["non-ascii", ["naïve", "日本"], "·", "naïve·日本"],
  ["astral-sep", ["a", "b"], "\u{1F642}", "a\u{1F642}b"],
  ["sep-in-item", ["a,b", "c"], ",", "a,b,c"],
];

const numberCases: [string, number[], string, string][] = [
  ["numbers", [1, 2, 3], ",", "1,2,3"],
  ["negative", [-1, 0, 1], " ", "-1 0 1"],
  ["empty", [], ",", ""],
  ["single", [42], ",", "42"],
  ["int32-ends", [2147483647, -2147483648], ";", "2147483647;-2147483648"],
];

for (const [name, items, sep, want] of cases) {
  test(name, () => {
    assert.equal(join(items, sep), want);
  });
}

for (const [name, items, sep, want] of numberCases) {
  test("numbers " + name, () => {
    assert.equal(joinNumbers(items, sep), want);
  });
}
join.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

// Package join joins a list of strings, and a list of numbers, with a separator.
package join

import (
	"strconv"
	"strings"
)

// Join returns the items with sep between each two.
func Join(items []string, sep string) string {
	return strings.Join(items, sep)
}

// JoinNumbers returns the decimal form of each item, with sep between each two.
func JoinNumbers(items []int32, sep string) string {
	// strings.Join takes only a []string, so the code converts each item.
	parts := make([]string, len(items))
	for i, n := range items {
		parts[i] = strconv.Itoa(int(n))
	}
	return strings.Join(parts, sep)
}
join_test.go 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

package join

import "testing"

func TestJoin(t *testing.T) {
	cases := []struct {
		name  string
		items []string
		sep   string
		want  string
	}{
		{"comma", []string{"a", "b", "c"}, ",", "a,b,c"},
		{"comma-space", []string{"red", "green", "blue"}, ", ", "red, green, blue"},
		{"words", []string{"Hello", "world"}, " ", "Hello world"},
		{"empty-list", []string{}, ",", ""},
		{"single", []string{"only"}, ",", "only"},
		{"empty-items", []string{"", "", ""}, ",", ",,"},
		{"empty-middle", []string{"a", "", "b"}, "-", "a--b"},
		{"empty-sep", []string{"a", "b", "c"}, "", "abc"},
		{"long-sep", []string{"x", "y"}, " -> ", "x -> y"},
		{"non-ascii", []string{"naïve", "日本"}, "·", "naïve·日本"},
		{"astral-sep", []string{"a", "b"}, "\U0001F642", "a\U0001F642b"},
		{"sep-in-item", []string{"a,b", "c"}, ",", "a,b,c"},
	}
	for _, c := range cases {
		if got := Join(c.items, c.sep); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}

func TestJoinNumbers(t *testing.T) {
	cases := []struct {
		name  string
		items []int32
		sep   string
		want  string
	}{
		{"numbers", []int32{1, 2, 3}, ",", "1,2,3"},
		{"negative", []int32{-1, 0, 1}, " ", "-1 0 1"},
		{"empty", []int32{}, ",", ""},
		{"single", []int32{42}, ",", "42"},
		{"int32-ends", []int32{2147483647, -2147483648}, ";", "2147483647;-2147483648"},
	}
	for _, c := range cases {
		if got := JoinNumbers(c.items, c.sep); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
join.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

/// Returns the items with sep between each two.
pub fn join(items: &[&str], sep: &str) -> String {
    // join on a slice of string slices makes one String of the right size.
    items.join(sep)
}

/// Returns the decimal form of each item, with sep between each two.
pub fn join_numbers(items: &[i32], sep: &str) -> String {
    // join needs items that can be borrowed as str, so the code converts each
    // number first.
    items.iter().map(i32::to_string).collect::<Vec<_>>().join(sep)
}
tests/join_test.rs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/join-a-list-of-strings/.

use algo_join_a_list_of_strings::{join, join_numbers};

#[test]
fn join_cases() {
    let cases: &[(&str, &[&str], &str, &str)] = &[
        ("comma", &["a", "b", "c"], ",", "a,b,c"),
        ("comma-space", &["red", "green", "blue"], ", ", "red, green, blue"),
        ("words", &["Hello", "world"], " ", "Hello world"),
        ("empty-list", &[], ",", ""),
        ("single", &["only"], ",", "only"),
        ("empty-items", &["", "", ""], ",", ",,"),
        ("empty-middle", &["a", "", "b"], "-", "a--b"),
        ("empty-sep", &["a", "b", "c"], "", "abc"),
        ("long-sep", &["x", "y"], " -> ", "x -> y"),
        ("non-ascii", &["naïve", "日本"], "·", "naïve·日本"),
        ("astral-sep", &["a", "b"], "\u{1F642}", "a\u{1F642}b"),
        ("sep-in-item", &["a,b", "c"], ",", "a,b,c"),
    ];
    for &(name, items, sep, want) in cases {
        assert_eq!(join(items, sep), want, "{name}");
    }
}

#[test]
fn join_numbers_cases() {
    let cases: &[(&str, &[i32], &str, &str)] = &[
        ("numbers", &[1, 2, 3], ",", "1,2,3"),
        ("negative", &[-1, 0, 1], " ", "-1 0 1"),
        ("empty", &[], ",", ""),
        ("single", &[42], ",", "42"),
        ("int32-ends", &[2147483647, -2147483648], ";", "2147483647;-2147483648"),
    ];
    for &(name, items, sep, want) in cases {
        assert_eq!(join_numbers(items, sep), want, "{name}");
    }
}
join.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/join-a-list-of-strings/.

# join SEP ITEM...: prints the items with SEP between each two. "${*}" uses
# only the first character of IFS, so the function loops for a separator of
# any length.
join() {
  local sep=$1 out="" item
  shift
  if (($# > 0)); then
    out=$1
    shift
  fi
  for item in "$@"; do
    out+="$sep$item"
  done
  printf '%s' "$out"
}

# join_numbers SEP N...: prints the decimal form of each integer N, with SEP
# between each two. printf %d checks that each item is an integer.
join_numbers() {
  local sep=$1 n
  shift
  local -a parts=()
  for n in "$@"; do
    parts+=("$(printf '%d' "$n")")
  done
  join "$sep" ${parts[@]+"${parts[@]}"}
}
test_join.bats 35 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/join-a-list-of-strings/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/join.sh"
}

check() { # check WANT COMMAND ARGS...
  local want=$1
  shift
  run "$@"
  [ "$status" -eq 0 ]
  [ "$output" = "$want" ]
}

@test "comma" { check 'a,b,c' join ',' a b c; }
@test "comma-space" { check 'red, green, blue' join ', ' red green blue; }
@test "words" { check 'Hello world' join ' ' Hello world; }
@test "empty-list" { check '' join ','; }
@test "single" { check 'only' join ',' only; }
@test "empty-items" { check ',,' join ',' '' '' ''; }
@test "empty-middle" { check 'a--b' join '-' a '' b; }
@test "empty-sep" { check 'abc' join '' a b c; }
@test "long-sep" { check 'x -> y' join ' -> ' x y; }
@test "non-ascii" { check 'naïve·日本' join '·' 'naïve' '日本'; }
@test "astral-sep" { check 'a🙂b' join '🙂' a b; }
@test "sep-in-item" { check 'a,b,c' join ',' 'a,b' c; }
@test "numbers" { check '1,2,3' join_numbers ',' 1 2 3; }
@test "negative" { check '-1 0 1' join_numbers ' ' -1 0 1; }
@test "empty-numbers" { check '' join_numbers ','; }
@test "single-number" { check '42' join_numbers ',' 42; }
@test "int32-ends" { check '2147483647;-2147483648' join_numbers ';' 2147483647 -2147483648; }

References

  1. The Python Standard Library, Built-in Types, str.join
  2. MDN Web Docs, Array.prototype.join(), Description
  3. Java SE 25 API, java.util.stream.Collectors, joining
  4. .NET API reference, String.Join method, Remarks
  5. Go standard library, package strings, Join
  6. The Rust Standard Library, primitive type slice, join, concat
  7. cppreference.com, std::ranges::views::join_with
  8. Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Special Parameters; Bash Builtin Commands, printf
  9. MDN Web Docs, Array.prototype.toString(), Description
  10. Java SE 25 API, java.lang.String, join(CharSequence, CharSequence...)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source