Taskintro
Concatenate strings
Also called string concatenation, join two strings, append a string, add strings, string plus operator, concat.
Join two strings into one with the operator or function of each language, and know the rules when one operand is a number or null and the cost of repeated concatenation.
- Evidence
- Code in 10 languages
Task
Concatenate two strings: make one string that holds the characters of a and then the characters of b, with nothing between them. The function concat(a, b) returns the result. A second function, concat_number(s, n), puts the decimal form of a 32-bit integer after a string, because each language has its own rule for a string and a number.
Concatenation does not change the two strings. In most languages a string is immutable, so the result is a new string. The cost of one concatenation is the sum of the two lengths, and a loop of concatenations can cost much more. The task "Build a string efficiently" covers that loop.
Solutions
| Language | Two strings | A string and a number |
|---|---|---|
| Python | a + b |
f"{s}{n}" or s + str(n) |
| JavaScript, TypeScript | a + b |
`${s}${n}` |
| Java | a + b |
s + n |
| C# | a + b |
s + n.ToString(CultureInfo.InvariantCulture) |
| Go | a + b |
s + strconv.Itoa(n) |
| Rust | a.to_owned() + b |
format!("{s}{n}") |
| C | malloc and memcpy |
snprintf |
| C++ | std::string and += |
std::format("{}{}", s, n) |
| Bash | "$a$b" |
"$s$n" |
- Python.
+joins twostrvalues. "Concatenating immutable sequences always results in a new object"1. Python does not convert a number for+, so the code uses a "formatted string literal or f-string"2. - JavaScript and TypeScript. "The addition (+) operator produces the sum of numeric operands or string concatenation"3.
concat"concatenates the string arguments to the calling string and returns a new string"4. The code uses a template literal for the number, because a template literal makes the conversion clear and has "string interpolation with embedded expressions"5. - Java. "If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time"6, so
s + ngives the digits ofn. The result "is newly created (§12.5) unless the expression is a constant expression (§15.29)"6. - C#. "When one or both operands are of type string, the + operator concatenates the string representations of its operands"7. The code calls
ToStringwithCultureInfo.InvariantCulture, so the culture of the machine cannot change the digits. - Go. "Strings can be concatenated using the + operator or the += assignment operator"8. Go has no implicit conversion, so the code calls
strconv.Itoa, which "is equivalent to FormatInt(int64(i), 10)"9. - Rust.
String + &str"consumes the String on the left-hand side and re-uses its buffer (growing it if necessary)"10, and "The string on the right-hand side is only borrowed"10. The function receives two&strvalues, so it makes an owned copy ofafirst.format!"Creates a String using interpolation of runtime expressions"11. - C. A C string is an array of bytes that ends with a null byte, and the language has no operator to join two of them.
strcat"Appends a copy of the null-terminated byte string pointed to by src to the end of the null-terminated byte string pointed to by dest"12, but the caller must supply a destination that is large enough. The code allocates the sum of the two lengths plus one byte, and copies each part withmemcpy. The caller frees the result. For the number,snprintfwith a size of 0 returns the length of the text, and a second call writes it. - C++.
operator+"Returns a string containing characters from lhs followed by the characters from rhs"13. The code takes twostd::string_viewvalues, reserves the sum of the two sizes and appends each part with+=.std::formatwrites the number14. - Bash. Two expansions side by side in one word make one string, so
"$1$2"is the concatenation. A Bash value is a string, so a number needs no conversion.printf '%d'checks that the argument is an integer.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl, and the cases of concat_number are in cases/number.jsonl.
empty-both,empty-leftandempty-right: the empty string is the identity of concatenation. The result is the other operand.non-asciiandastral: the bytes ofïand🙂do not change. In every unit, the length of the result is the sum of the two lengths.combining-mark:"e"and the combining acute accent U+0301 give"é", which a reader sees as one character. The result has the same code points as the operands, but the graphemes at the boundary can join, so the number of graphemes is not always the sum.flag-halves: the two regional indicators🇫and🇷give the flag🇫🇷. Two strings of one grapheme each make one grapheme.digit-strings:"1"and"2"give"12", not3. The operands are strings, so no language adds them.int32-minandnegative: the result has the minus sign U+002D and no space.int32-minis-2147483648, which has no positive 32-bit form, so code that writes the sign and then the digits of-nfails for it.
Pitfalls
- JavaScript
+with a string and a number. "If one side is a string, the other operand is also converted to a string"3, and+groups from the left. So'1' + 2 + 3is'123', but1 + 2 + '3'is'33'.-has no string form, so'5' - 2is3:
console.log("1" + 2 + 3);
console.log(1 + 2 + "3");
console.log("5" - 2);
console.log(`${1 + 2}3`);
123
33
3
33
- Java
+groups from the left, andnullbecomes text. The "additive operators have the same precedence and are syntactically left-associative (they group left-to-right)"6, so Java gives the same results as JavaScript. String conversion turns anullreference into the textnull.concatdoes not, because "passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown"15:
public class Main {
public static void main(String[] args) {
System.out.println("1" + 2 + 3);
System.out.println(1 + 2 + "3");
String name = null;
System.out.println("Hello, " + name);
try {
System.out.println("Hello, ".concat(name));
} catch (NullPointerException e) {
System.out.println("concat: " + e.getClass().getSimpleName());
}
}
}
123
33
Hello, null
concat: NullPointerException
- C#
nullis an empty string. In a concatenation, "the string representation of null is an empty string"7, so a missing name gives"Hello, !"and no error.string.Concatalso skips anullargument:
string? name = null;
Console.WriteLine("Hello, " + name + "!");
Console.WriteLine(1 + 2 + "3");
Console.WriteLine("1" + 2 + 3);
Console.WriteLine(string.Concat("a", null, "b"));
Hello, !
33
123
ab
- Python does not convert a number for
+."items: " + 3raisesTypeError. Usestr(n)or an f-string:
count = 3
try:
print("items: " + count)
except TypeError as e:
print(type(e).__name__)
print("items: " + str(count))
print(f"items: {count}")
TypeError
items: 3
items: 3
- Go
string(n)makes a character, not digits. The conversion of an integer to a string "yields a string containing the (possibly multi-byte) UTF-8 representation of the Unicode code point with the given integer value"8, sostring(rune(65))is"A". "The go vet tool flags certain integer-to-string conversions as potential errors"8. Usestrconv.Itoaorfmt.Sprint:
package main
import (
"fmt"
"strconv"
)
func main() {
n := 65
fmt.Println("n=" + string(rune(n)))
fmt.Println("n=" + strconv.Itoa(n))
fmt.Println("n=" + fmt.Sprint(n))
}
n=A
n=65
n=65
- C needs room for the result. For
strcat, "The behavior is undefined if the destination array is not large enough for the contents of both src and dest and the terminating null character"12.snprintfnever writes past its buffer. It returns the "number of characters (not including the terminating null character) which would have been written to buffer if bufsz was ignored"16, so a return value that is not less than the size tells you that the text was cut:
#include <stdio.h>
int main(void) {
char buf[8];
int n = snprintf(buf, sizeof buf, "%s%s", "Hello, ", "world");
printf("%d [%s]\n", n, buf);
}
12 [Hello, ]
- C++
+on a literal and a number. A string literal is an array ofchar, so"abc" + 1is a pointer to the second character, and it gives"bc".s += 65appends thecharwith the value 65, so it appendsA. Make the left operand astd::string, and convert a number withstd::formatorstd::to_string:
#include <print>
#include <string>
int main() {
std::string s = "n=";
s += 65;
std::println("{}", s);
std::println("{}", "abc" + 1);
std::println("{}", std::string("abc") + "1");
}
n=A
bc
abc1
- Bash
+=depends on the integer attribute. "When applied to a string-valued variable, value is expanded and appended to the variable’s value"17. When "the integer attribute has been set", the two values are evaluated as arithmetic expressions and added17. So+=gives12for a plain variable and3afterdeclare -i:
total=1
total+=2
echo "$total"
declare -i sum=1
sum+=2
echo "$sum"
greeting="Hello, "
greeting+="world"
echo "$greeting"
12
3
Hello, world
- Repeated concatenation in a loop. Each concatenation of immutable strings copies both parts. In Python, "building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length"1, and the documentation says that "you can build a list and use str.join() at the end"1. In C#, "Each + or += operation creates a new string, because strings are immutable"18. Rust re-uses the buffer of the left
Stringto avoid the copy, which otherwise "would lead to O(n^2) running time when building an n-byte string by repeated concatenation"10. For a loop, use a builder or a join. The task Build a string efficiently shows them.
Related tasks
- Split a string: a split is the reverse of a join, which concatenates many strings with a separator between them.
- Find the length of a string: the length of a concatenation is the sum of the two lengths in bytes, code units and code points, but not always in graphemes.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-strings/.
def concat(a: str, b: str) -> str:
"""Return the characters of a followed by the characters of b."""
return a + b
def concat_number(s: str, n: int) -> str:
"""Return s followed by the decimal form of n."""
# str + int raises TypeError, so the f-string converts n.
return f"{s}{n}"
test_concatenate.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-strings/.
import pytest
from concatenate import concat, concat_number
CASES = {
"hello-world": ("Hello, ", "world", "Hello, world"),
"two-words": ("good", "bye", "goodbye"),
"keep-spaces": ("a ", " b", "a b"),
"empty-both": ("", "", ""),
"empty-left": ("", "abc", "abc"),
"empty-right": ("abc", "", "abc"),
"non-ascii": ("naï", "ve", "naïve"),
"astral": ("a", "🙂", "a🙂"),
"combining-mark": ("e", "\u0301", "e\u0301"),
"flag-halves": ("\U0001f1eb", "\U0001f1f7", "🇫🇷"),
"digit-strings": ("1", "2", "12"),
}
NUMBER_CASES = {
"positive": ("item", 3, "item3"),
"zero": ("n=", 0, "n=0"),
"negative": ("x", -5, "x-5"),
"empty-prefix": ("", 42, "42"),
"int32-max": ("max=", 2147483647, "max=2147483647"),
"int32-min": ("min=", -2147483648, "min=-2147483648"),
}
@pytest.mark.parametrize("name", CASES)
def test_concat(name):
a, b, want = CASES[name]
assert concat(a, b) == want
@pytest.mark.parametrize("name", NUMBER_CASES)
def test_concat_number(name):
s, n, want = NUMBER_CASES[name]
assert concat_number(s, n) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
#include "concatenate.hpp"
#include <format>
std::string concat(std::string_view a, std::string_view b) {
// operator+ takes std::string operands, so the code builds one string
// with room for both parts.
std::string r;
r.reserve(a.size() + b.size());
r += a;
r += b;
return r;
}
std::string concat_number(std::string_view s, std::int32_t n) {
// std::format writes the decimal digits without a locale.
return std::format("{}{}", s, n);
}
concatenate.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
#pragma once
#include <cstdint>
#include <string>
#include <string_view>
// Returns the bytes of a followed by the bytes of b.
std::string concat(std::string_view a, std::string_view b);
// Returns s followed by the decimal form of n.
std::string concat_number(std::string_view s, std::int32_t n);
test_concatenate.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
#include <cstdint>
#include <cstdio>
#include <limits>
#include <string>
#include <string_view>
#include "concatenate.hpp"
namespace {
int failures = 0;
void check(std::string_view name, const std::string& got, std::string_view want) {
if (got != want) {
std::fprintf(stderr, "case %.*s failed\n", static_cast<int>(name.size()), name.data());
++failures;
}
}
} // namespace
int main() {
check("hello-world", concat("Hello, ", "world"), "Hello, world");
check("two-words", concat("good", "bye"), "goodbye");
check("keep-spaces", concat("a ", " b"), "a b");
check("empty-both", concat("", ""), "");
check("empty-left", concat("", "abc"), "abc");
check("empty-right", concat("abc", ""), "abc");
check("non-ascii", concat("naï", "ve"), "naïve");
check("astral", concat("a", "🙂"), "a🙂");
check("combining-mark", concat("e", "\xcc\x81"), "e\xcc\x81");
check("flag-halves", concat("🇫", "🇷"), "🇫🇷");
check("digit-strings", concat("1", "2"), "12");
check("positive", concat_number("item", 3), "item3");
check("zero", concat_number("n=", 0), "n=0");
check("negative", concat_number("x", -5), "x-5");
check("empty-prefix", concat_number("", 42), "42");
check("int32-max", concat_number("max=", std::numeric_limits<std::int32_t>::max()), "max=2147483647");
check("int32-min", concat_number("min=", std::numeric_limits<std::int32_t>::min()), "min=-2147483648");
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
/** Concatenates two strings, and a string and a number. */
public final class Concatenate {
private Concatenate() {}
/** Returns the characters of a followed by the characters of b. */
public static String concat(String a, String b) {
return a + b;
}
/** Returns s followed by the decimal form of n. */
public static String concatNumber(String s, int n) {
// One String operand makes + a string concatenation, so n is converted.
return s + n;
}
}
ConcatenateTest.java 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
import static org.junit.jupiter.api.Assertions.assertEquals;
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 ConcatenateTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("hello-world", "Hello, ", "world", "Hello, world"),
Arguments.of("two-words", "good", "bye", "goodbye"),
Arguments.of("keep-spaces", "a ", " b", "a b"),
Arguments.of("empty-both", "", "", ""),
Arguments.of("empty-left", "", "abc", "abc"),
Arguments.of("empty-right", "abc", "", "abc"),
Arguments.of("non-ascii", "naï", "ve", "naïve"),
Arguments.of("astral", "a", "🙂", "a🙂"),
Arguments.of("combining-mark", "e", "\u0301", "e\u0301"),
Arguments.of("flag-halves", "🇫", "🇷", "🇫🇷"),
Arguments.of("digit-strings", "1", "2", "12"));
}
static Stream<Arguments> numberCases() {
return Stream.of(
Arguments.of("positive", "item", 3, "item3"),
Arguments.of("zero", "n=", 0, "n=0"),
Arguments.of("negative", "x", -5, "x-5"),
Arguments.of("empty-prefix", "", 42, "42"),
Arguments.of("int32-max", "max=", 2147483647, "max=2147483647"),
Arguments.of("int32-min", "min=", -2147483648, "min=-2147483648"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void concat(String name, String a, String b, String want) {
assertEquals(want, Concatenate.concat(a, b), name);
}
@ParameterizedTest(name = "{0}")
@MethodSource("numberCases")
void concatNumber(String name, String s, int n, String want) {
assertEquals(want, Concatenate.concatNumber(s, n), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
#include "concatenate.h"
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(const char *a, const char *b) {
size_t na = strlen(a), nb = strlen(b);
char *r = malloc(na + nb + 1);
if (r == NULL) {
return NULL;
}
// memcpy with the known lengths copies each byte once. strcat would scan
// the destination again to find its end.
memcpy(r, a, na);
memcpy(r + na, b, nb + 1);
return r;
}
char *concat_number(const char *s, int32_t n) {
// A call with no buffer returns the length that the text needs.
int len = snprintf(NULL, 0, "%s%" PRId32, s, n);
if (len < 0) {
return NULL;
}
char *r = malloc((size_t)len + 1);
if (r == NULL) {
return NULL;
}
snprintf(r, (size_t)len + 1, "%s%" PRId32, s, n);
return r;
}
concatenate.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
#ifndef CONCATENATE_H
#define CONCATENATE_H
#include <stdint.h>
// concat returns a new null-terminated string that holds the bytes of a
// followed by the bytes of b, or NULL if there is no memory. The caller frees
// the result.
char *concat(const char *a, const char *b);
// concat_number returns a new null-terminated string that holds s followed by
// the decimal form of n, or NULL if there is no memory. The caller frees the
// result.
char *concat_number(const char *s, int32_t n);
#endif
test_concatenate.c 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
#include "concatenate.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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) {
check("hello-world", concat("Hello, ", "world"), "Hello, world");
check("two-words", concat("good", "bye"), "goodbye");
check("keep-spaces", concat("a ", " b"), "a b");
check("empty-both", concat("", ""), "");
check("empty-left", concat("", "abc"), "abc");
check("empty-right", concat("abc", ""), "abc");
check("non-ascii", concat("naï", "ve"), "naïve");
check("astral", concat("a", "🙂"), "a🙂");
// U+0301 COMBINING ACUTE ACCENT is CC 81 in UTF-8.
check("combining-mark", concat("e", "\xcc\x81"), "e\xcc\x81");
check("flag-halves", concat("🇫", "🇷"), "🇫🇷");
check("digit-strings", concat("1", "2"), "12");
check("positive", concat_number("item", 3), "item3");
check("zero", concat_number("n=", 0), "n=0");
check("negative", concat_number("x", -5), "x-5");
check("empty-prefix", concat_number("", 42), "42");
check("int32-max", concat_number("max=", INT32_MAX), "max=2147483647");
check("int32-min", concat_number("min=", INT32_MIN), "min=-2147483648");
if (failures != 0) {
return 1;
}
puts("ok");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
using System.Globalization;
/// <summary>Concatenates two strings, and a string and a number.</summary>
public static class Concatenate
{
/// <summary>Returns the characters of a followed by the characters of b.</summary>
public static string Concat(string a, string b) => a + b;
/// <summary>Returns s followed by the decimal form of n.</summary>
// s + n would format n with the current culture. The invariant culture
// gives the same digits and minus sign on every machine.
public static string ConcatNumber(string s, int n) => s + n.ToString(CultureInfo.InvariantCulture);
}
ConcatenateTests.cs 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
using Xunit;
public sealed class ConcatenateTests
{
public static TheoryData<string, string, string, string> Cases => new()
{
{ "hello-world", "Hello, ", "world", "Hello, world" },
{ "two-words", "good", "bye", "goodbye" },
{ "keep-spaces", "a ", " b", "a b" },
{ "empty-both", "", "", "" },
{ "empty-left", "", "abc", "abc" },
{ "empty-right", "abc", "", "abc" },
{ "non-ascii", "naï", "ve", "naïve" },
{ "astral", "a", "🙂", "a🙂" },
{ "combining-mark", "e", "\u0301", "e\u0301" },
{ "flag-halves", "🇫", "🇷", "🇫🇷" },
{ "digit-strings", "1", "2", "12" },
};
public static TheoryData<string, string, int, string> NumberCases => new()
{
{ "positive", "item", 3, "item3" },
{ "zero", "n=", 0, "n=0" },
{ "negative", "x", -5, "x-5" },
{ "empty-prefix", "", 42, "42" },
{ "int32-max", "max=", 2147483647, "max=2147483647" },
{ "int32-min", "min=", -2147483648, "min=-2147483648" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Concat(string name, string a, string b, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Concatenate.Concat(a, b));
}
[Theory]
[MemberData(nameof(NumberCases))]
public void ConcatNumber(string name, string s, int n, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Concatenate.ConcatNumber(s, n));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
/** Returns the characters of a followed by the characters of b. */
export function concat(a, b) {
return a + b;
}
/** Returns s followed by the decimal form of n. */
export function concatNumber(s, n) {
// A template literal converts n to a string. With +, the result depends on
// the order of the operands (see Pitfalls).
return `${s}${n}`;
}
concatenate.test.js 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { concat, concatNumber } from "./concatenate.js";
const cases = [
["hello-world", "Hello, ", "world", "Hello, world"],
["two-words", "good", "bye", "goodbye"],
["keep-spaces", "a ", " b", "a b"],
["empty-both", "", "", ""],
["empty-left", "", "abc", "abc"],
["empty-right", "abc", "", "abc"],
["non-ascii", "naï", "ve", "naïve"],
["astral", "a", "🙂", "a🙂"],
["combining-mark", "e", "\u0301", "e\u0301"],
["flag-halves", "\u{1f1eb}", "\u{1f1f7}", "🇫🇷"],
["digit-strings", "1", "2", "12"],
];
const numberCases = [
["positive", "item", 3, "item3"],
["zero", "n=", 0, "n=0"],
["negative", "x", -5, "x-5"],
["empty-prefix", "", 42, "42"],
["int32-max", "max=", 2147483647, "max=2147483647"],
["int32-min", "min=", -2147483648, "min=-2147483648"],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.equal(concat(a, b), want);
});
}
for (const [name, s, n, want] of numberCases) {
test(`number ${name}`, () => {
assert.equal(concatNumber(s, n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
/** Returns the characters of a followed by the characters of b. */
export function concat(a: string, b: string): string {
return a + b;
}
/** Returns s followed by the decimal form of n. */
export function concatNumber(s: string, n: number): string {
// A template literal converts n to a string. With +, the result depends on
// the order of the operands (see Pitfalls).
return `${s}${n}`;
}
concatenate.test.ts 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { concat, concatNumber } from "./concatenate.ts";
const cases: [string, string, string, string][] = [
["hello-world", "Hello, ", "world", "Hello, world"],
["two-words", "good", "bye", "goodbye"],
["keep-spaces", "a ", " b", "a b"],
["empty-both", "", "", ""],
["empty-left", "", "abc", "abc"],
["empty-right", "abc", "", "abc"],
["non-ascii", "naï", "ve", "naïve"],
["astral", "a", "🙂", "a🙂"],
["combining-mark", "e", "\u0301", "e\u0301"],
["flag-halves", "\u{1f1eb}", "\u{1f1f7}", "🇫🇷"],
["digit-strings", "1", "2", "12"],
];
const numberCases: [string, string, number, string][] = [
["positive", "item", 3, "item3"],
["zero", "n=", 0, "n=0"],
["negative", "x", -5, "x-5"],
["empty-prefix", "", 42, "42"],
["int32-max", "max=", 2147483647, "max=2147483647"],
["int32-min", "min=", -2147483648, "min=-2147483648"],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.equal(concat(a, b), want);
});
}
for (const [name, s, n, want] of numberCases) {
test(`number ${name}`, () => {
assert.equal(concatNumber(s, n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
// Package concatenate joins two strings, and a string and a number.
package concatenate
import "strconv"
// Concat returns the bytes of a followed by the bytes of b.
func Concat(a, b string) string {
return a + b
}
// ConcatNumber returns s followed by the decimal form of n.
func ConcatNumber(s string, n int32) string {
// Go has no implicit conversion, and string(n) makes a code point, not
// digits, so the code calls strconv.
return s + strconv.Itoa(int(n))
}
concatenate_test.go 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
package concatenate
import "testing"
func TestConcat(t *testing.T) {
cases := []struct{ name, a, b, want string }{
{"hello-world", "Hello, ", "world", "Hello, world"},
{"two-words", "good", "bye", "goodbye"},
{"keep-spaces", "a ", " b", "a b"},
{"empty-both", "", "", ""},
{"empty-left", "", "abc", "abc"},
{"empty-right", "abc", "", "abc"},
{"non-ascii", "naï", "ve", "naïve"},
{"astral", "a", "🙂", "a🙂"},
{"combining-mark", "e", "\u0301", "e\u0301"},
{"flag-halves", "🇫", "🇷", "🇫🇷"},
{"digit-strings", "1", "2", "12"},
}
for _, c := range cases {
if got := Concat(c.a, c.b); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
func TestConcatNumber(t *testing.T) {
cases := []struct {
name, s string
n int32
want string
}{
{"positive", "item", 3, "item3"},
{"zero", "n=", 0, "n=0"},
{"negative", "x", -5, "x-5"},
{"empty-prefix", "", 42, "42"},
{"int32-max", "max=", 2147483647, "max=2147483647"},
{"int32-min", "min=", -2147483648, "min=-2147483648"},
}
for _, c := range cases {
if got := ConcatNumber(c.s, c.n); got != c.want {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
//! Concatenate two strings, and a string and a number.
/// Returns the characters of `a` followed by the characters of `b`.
pub fn concat(a: &str, b: &str) -> String {
// String + &str takes the String on the left and appends to its buffer,
// so the code makes an owned copy of a first.
a.to_owned() + b
}
/// Returns `s` followed by the decimal form of `n`.
pub fn concat_number(s: &str, n: i32) -> String {
format!("{s}{n}")
}
tests/concatenate_test.rs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/concatenate-strings/.
use algo_concatenate_strings::{concat, concat_number};
#[test]
fn concat_cases() {
let cases = [
("hello-world", "Hello, ", "world", "Hello, world"),
("two-words", "good", "bye", "goodbye"),
("keep-spaces", "a ", " b", "a b"),
("empty-both", "", "", ""),
("empty-left", "", "abc", "abc"),
("empty-right", "abc", "", "abc"),
("non-ascii", "naï", "ve", "naïve"),
("astral", "a", "🙂", "a🙂"),
("combining-mark", "e", "\u{301}", "e\u{301}"),
("flag-halves", "\u{1f1eb}", "\u{1f1f7}", "🇫🇷"),
("digit-strings", "1", "2", "12"),
];
for (name, a, b, want) in cases {
assert_eq!(concat(a, b), want, "case {name}");
}
}
#[test]
fn concat_number_cases() {
let cases = [
("positive", "item", 3, "item3"),
("zero", "n=", 0, "n=0"),
("negative", "x", -5, "x-5"),
("empty-prefix", "", 42, "42"),
("int32-max", "max=", i32::MAX, "max=2147483647"),
("int32-min", "min=", i32::MIN, "min=-2147483648"),
];
for (name, s, n, want) in cases {
assert_eq!(concat_number(s, n), want, "case {name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-strings/.
# concat A B: prints A followed by B. Two expansions side by side make one
# word, so "$1$2" is the concatenation.
concat() {
printf '%s' "$1$2"
}
# concat_number S N: prints S followed by the decimal form of the integer N.
# A Bash value is a string, so a number needs no conversion. %d checks that N
# is an integer.
concat_number() {
printf '%s%d' "$1" "$2"
}
test_concatenate.bats 36 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/concatenate-strings/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/concatenate.sh"
}
check() { # check WANT COMMAND ARGS...
local want=$1
shift
run "$@"
[ "$status" -eq 0 ]
[ "$output" = "$want" ]
}
@test "hello-world" { check 'Hello, world' concat 'Hello, ' 'world'; }
@test "two-words" { check 'goodbye' concat 'good' 'bye'; }
@test "keep-spaces" { check 'a b' concat 'a ' ' b'; }
@test "empty-both" { check '' concat '' ''; }
@test "empty-left" { check 'abc' concat '' 'abc'; }
@test "empty-right" { check 'abc' concat 'abc' ''; }
@test "non-ascii" { check 'naïve' concat 'naï' 've'; }
@test "astral" { check 'a🙂' concat 'a' '🙂'; }
# U+0301 COMBINING ACUTE ACCENT is CC 81 in UTF-8.
@test "combining-mark" { check $'e\xcc\x81' concat 'e' $'\xcc\x81'; }
@test "flag-halves" { check '🇫🇷' concat '🇫' '🇷'; }
@test "digit-strings" { check '12' concat '1' '2'; }
@test "number positive" { check 'item3' concat_number 'item' 3; }
@test "number zero" { check 'n=0' concat_number 'n=' 0; }
@test "number negative" { check 'x-5' concat_number 'x' -5; }
@test "number empty-prefix" { check '42' concat_number '' 42; }
@test "number int32-max" { check 'max=2147483647' concat_number 'max=' 2147483647; }
@test "number int32-min" { check 'min=-2147483648' concat_number 'min=' -2147483648; }
References
- The Python Standard Library, Built-in Types, Common Sequence Operations, note 6
- The Python Language Reference, Lexical analysis, f-strings
- MDN Web Docs, Addition (+), Description
- MDN Web Docs, String.prototype.concat(), Description
- MDN Web Docs, Template literals (Template strings)
- The Java Language Specification, Java SE 25 Edition, Chapter 15, Expressions, 15.18, Additive Operators; 15.18.1, String Concatenation Operator +
- C# language reference, Addition operators + and +=, String concatenation
- The Go Programming Language Specification, String concatenation; Conversions to and from a string type
- Go standard library, package strconv, Itoa
- The Rust Standard Library, struct String, impl Add<&str> for String
- The Rust Standard Library, macro format
- cppreference.com, strcat, strcat_s
- cppreference.com, std::operator+(std::basic_string)
- cppreference.com, std::format
- Java SE 25 API, java.lang.String, Class description; concat(String)
- cppreference.com, printf, fprintf, sprintf, snprintf, Return value
- Bash Reference Manual, on the site of the Bash maintainer Chet Ramey, Shell Parameters
- C# fundamentals, How to concatenate multiple strings
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag V1CQDW Edit this page History Report an error Markdown