Taskintro
Repeat a string
Also called string repeat, repeat, multiply a string, string times n, replicate a string, str_repeat.
Make a string of n copies of a string, and know what each language does with a count of 0, a negative count and a count that overflows.
- Evidence
- Code in 10 languages
Task
Make a string of n copies of the string s. The function repeat(s, n) returns the copies joined with nothing between them. For example, repeat("ab", 3) is ababab, and repeat("-", 5) is -----. If n is 0 or s is empty, the result is the empty string.
The count n is from 0 to 1000 in the contract. A negative count is not in the contract, because the languages do not agree on it. The result has len(s) * n units, so the code can reserve the memory one time.
Solutions
| Language | Repeat | Note |
|---|---|---|
| Python | s * n |
a negative n gives the empty string |
| JavaScript, TypeScript | s.repeat(n) |
a negative n throws RangeError |
| Java | s.repeat(n) |
a negative n throws |
| C# | a StringBuilder with the full capacity |
new string(c, n) is only for one char |
| Go | strings.Repeat(s, n) |
a negative n panics |
| Rust | s.repeat(n) |
n is a usize, so it is never negative |
| C | malloc, then memcpy n times |
check that len * n does not overflow |
| C++ | reserve, then += n times |
std::string(n, c) is only for one char |
| Bash | a loop with += |
- Python. The
*operator of a sequence and an int repeats the sequence. "Values of n less than 0 are treated as 0 (which yields an empty sequence of the same type as s)"1. - JavaScript and TypeScript.
repeatreturns a new string "containing the specified number of copies of the given string"2. - Java.
repeatreturns "a string whose value is the concatenation of this string repeated count times"3. It is in Java 11 and later. - C#.
string.Concat(Enumerable.Repeat(s, n))also works.Enumerable.Repeatgives "a sequence that contains one repeated value"4. - Go. "Repeat returns a new string consisting of count copies of the string s"5.
- Rust.
repeatmakes "a new String by repeating a string n times"6. - C. The code finds the length one time, allocates
len * n + 1bytes, and copiessto each place. - C++.
reserveallocates the memory one time, so each+=does not allocate again. - Bash. The loop appends
sto a variablentimes, andprintf '%s'prints it with no newline.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero: 0 copies ofabcis the empty string.emptyandempty-zero: copies of the empty string are the empty string.many: 100 copies ofabare 200 characters. The expected value in each test is one literal, so the test does not use the repeat of the language.astral: 3 copies of an emoji above U+FFFF are 3 code points, 6 UTF-16 units and 12 UTF-8 bytes.combining:efollowed by U+0301, 2 times, is 2 graphemes and 4 code points. The repeat copies code units, so each copy stays whole.
Pitfalls
- Python repeats the references. A negative count gives the empty string with no error. For a list, "items in the sequence s are not copied; they are referenced multiple times"1, so the 3 rows are one list:
print(repr("ab" * -1))
rows = [[]] * 3
rows[0].append(1)
print(rows)
''
[[1], [1], [1]]
- JavaScript changes the count to an integer. A count of 3.5 gives 3 copies "(count will be converted to integer)"2. A
RangeErroris thrown "if count is negative or if count overflows maximum string length"2:
console.log("ab".repeat(2.9));
try {
"ab".repeat(-1);
} catch (e) {
console.log(e.name);
}
abab
RangeError
- Java repeat throws for a negative count. It throws "IllegalArgumentException - if the count is negative"3. Check the count first if it comes from a user:
public class Main {
public static void main(String[] args) {
System.out.println("ab".repeat(3));
try {
"ab".repeat(-1);
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException");
}
}
}
ababab
IllegalArgumentException
- C# has a constructor only for one char.
new string('-', 5)makes a string "to the value indicated by a specified Unicode character repeated a specified number of times"7. For a string of more than one char, useEnumerable.Repeator aStringBuilder:
using System;
using System.Linq;
Console.WriteLine(new string('-', 5));
Console.WriteLine(string.Concat(Enumerable.Repeat("ab", 3)));
-----
ababab
- Go strings.Repeat panics. "It panics if count is negative or if the result of (len(s) * count) overflows"5:
package main
import (
"fmt"
"strings"
)
func main() {
defer func() {
fmt.Println("panic:", recover())
}()
fmt.Println(strings.Repeat("ab", 3))
fmt.Println(strings.Repeat("ab", -1))
}
ababab
panic: strings: negative Repeat count
- Rust repeat panics on overflow. "This function will panic if the capacity would overflow"6.
checked_mulgivesNoneif the length is too large, so the code can check before the call:
fn main() {
let s = "ab";
println!("{}", s.repeat(3));
println!("{:?}", s.len().checked_mul(usize::MAX));
}
ababab
None
- C size_t wraps on overflow.
len * nis an unsigned product, so it can wrap to a small number, and thenmallocgives too little memory. Comparenwith(SIZE_MAX - 1) / lenfirst:
#include <stdint.h>
#include <stdio.h>
int main(void) {
size_t len = 2;
size_t n = SIZE_MAX / 2 + 1;
printf("%zu\n", len * n);
printf("%d\n", n > (SIZE_MAX - 1) / len);
return 0;
}
0
1
- C++ std::string(n, c) is for one char. The constructor makes "a string with count copies of character ch"8. For a string, append it in a loop:
#include <iostream>
#include <string>
int main() {
std::cout << std::string(5, '-') << "\n";
std::string out;
for (int i = 0; i < 3; i++) {
out += "ab";
}
std::cout << out << "\n";
}
-----
ababab
- Bash
{1..$n}does not use the variable. "Brace expansion is performed before any other expansions"9, so$nis not yet a number, and the text stays as it is. Use a loop with((:
n=3
echo {1..$n}
out=''
for ((i = 0; i < n; i++)); do
out+='ab'
done
echo "$out"
{1..3}
ababab
Related tasks
- Build a string efficiently: reserve the memory before many appends.
- Concatenate strings: join two strings, the step that a repeat does
ntimes. - Join a list of strings: put a separator between the copies.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/repeat-a-string/.
"""Repeat a string."""
def repeat(s: str, n: int) -> str:
"""Return n copies of s. The * operator of a str and an int repeats it."""
return s * n
test_repeat.py 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/repeat-a-string/.
import pytest
from repeat import repeat
# The case many has the 200 chars of 100 copies of ab in one literal.
CASES = {
"word": ("ab", 3, "ababab"),
"one": ("abc", 1, "abc"),
"dash": ("-", 5, "-----"),
"zero": ("abc", 0, ""),
"empty": ("", 5, ""),
"empty-zero": ("", 0, ""),
"many": ("ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab"),
"astral": ("\U0001f642", 3, "\U0001f642\U0001f642\U0001f642"),
"combining": ("e\u0301", 2, "e\u0301e\u0301"),
}
@pytest.mark.parametrize("name", CASES)
def test_repeat(name):
s, n, want = CASES[name]
assert repeat(s, n) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
#include "repeat.hpp"
// std::string has a constructor for n copies of one char, but not for n copies
// of a string, so the function reserves the length and appends s n times.
std::string repeat(std::string_view s, std::size_t n) {
std::string out;
out.reserve(s.size() * n);
for (std::size_t i = 0; i < n; i++) {
out += s;
}
return out;
}
repeat.hpp 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
#ifndef REPEAT_HPP
#define REPEAT_HPP
#include <cstddef>
#include <string>
#include <string_view>
// repeat returns n copies of s.
std::string repeat(std::string_view s, std::size_t n);
#endif
test_repeat.cpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
#include "repeat.hpp"
#include <iostream>
#include <string>
#include <string_view>
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++;
}
}
// The case many has the 200 chars of 100 copies of ab in one literal.
int main() {
check("word", repeat("ab", 3), "ababab");
check("one", repeat("abc", 1), "abc");
check("dash", repeat("-", 5), "-----");
check("zero", repeat("abc", 0), "");
check("empty", repeat("", 5), "");
check("empty-zero", repeat("", 0), "");
check("many", repeat("ab", 100), "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab");
check("astral", repeat("\xf0\x9f\x99\x82", 3), "\xf0\x9f\x99\x82\xf0\x9f\x99\x82\xf0\x9f\x99\x82");
check("combining", repeat("e\xcc\x81", 2), "e\xcc\x81" "e\xcc\x81");
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
/** Repeats a string. */
public final class Repeat {
private Repeat() {}
/** Returns n copies of s. String.repeat throws if n is negative. */
public static String repeat(String s, int n) {
return s.repeat(n);
}
}
RepeatTest.java 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
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 RepeatTest {
// The case many has the 200 chars of 100 copies of ab in one literal.
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("word", "ab", 3, "ababab"),
Arguments.of("one", "abc", 1, "abc"),
Arguments.of("dash", "-", 5, "-----"),
Arguments.of("zero", "abc", 0, ""),
Arguments.of("empty", "", 5, ""),
Arguments.of("empty-zero", "", 0, ""),
Arguments.of("many", "ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab"),
Arguments.of("astral", "\ud83d\ude42", 3, "\ud83d\ude42\ud83d\ude42\ud83d\ude42"),
Arguments.of("combining", "e\u0301", 2, "e\u0301e\u0301"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void repeat(String name, String s, int n, String want) {
assertEquals(want, Repeat.repeat(s, n));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
#include "repeat.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
char *repeat(const char *s, size_t n) {
size_t len = strlen(s);
// len * n + 1 must not overflow size_t.
if (len != 0 && n > (SIZE_MAX - 1) / len) {
return NULL;
}
char *out = malloc(len * n + 1);
if (out == NULL) {
return NULL;
}
for (size_t i = 0; i < n; i++) {
memcpy(out + i * len, s, len);
}
out[len * n] = '\0';
return out;
}
repeat.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
#ifndef REPEAT_H
#define REPEAT_H
#include <stddef.h>
// repeat returns a new string with n copies of s, or NULL if there is no
// memory or the length overflows. The caller frees the result.
char *repeat(const char *s, size_t n);
#endif
test_repeat.c 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
#include "repeat.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
// check frees got, which is a new string from repeat.
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);
}
// The case many has the 200 chars of 100 copies of ab in one literal.
int main(void) {
check("word", repeat("ab", 3), "ababab");
check("one", repeat("abc", 1), "abc");
check("dash", repeat("-", 5), "-----");
check("zero", repeat("abc", 0), "");
check("empty", repeat("", 5), "");
check("empty-zero", repeat("", 0), "");
check("many", repeat("ab", 100), "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab");
check("astral", repeat("\xf0\x9f\x99\x82", 3), "\xf0\x9f\x99\x82\xf0\x9f\x99\x82\xf0\x9f\x99\x82");
check("combining", repeat("e\xcc\x81", 2), "e\xcc\x81" "e\xcc\x81");
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
using System.Text;
/// <summary>Repeats a string.</summary>
public static class StringRepeat
{
/// <summary>
/// Returns n copies of s. The string type has no repeat method for a
/// string, so the code appends s to a StringBuilder with the full capacity.
/// </summary>
public static string Repeat(string s, int n)
{
var sb = new StringBuilder(s.Length * n);
for (int i = 0; i < n; i++)
{
sb.Append(s);
}
return sb.ToString();
}
}
RepeatTests.cs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
using Xunit;
public sealed class RepeatTests
{
// The case many has the 200 chars of 100 copies of ab in one literal.
public static TheoryData<string, string, int, string> Cases => new()
{
{ "word", "ab", 3, "ababab" },
{ "one", "abc", 1, "abc" },
{ "dash", "-", 5, "-----" },
{ "zero", "abc", 0, "" },
{ "empty", "", 5, "" },
{ "empty-zero", "", 0, "" },
{ "many", "ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab" },
{ "astral", "\U0001f642", 3, "\U0001f642\U0001f642\U0001f642" },
{ "combining", "e\u0301", 2, "e\u0301e\u0301" },
};
[Theory]
[MemberData(nameof(Cases))]
public void Repeat(string name, string s, int n, string want)
{
Assert.NotNull(name);
Assert.Equal(want, StringRepeat.Repeat(s, n));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
// repeat returns n copies of s. String.prototype.repeat throws a RangeError
// if n is negative.
export function repeat(s, n) {
return s.repeat(n);
}
repeat.test.js 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { repeat } from "./repeat.js";
// The case many has the 200 chars of 100 copies of ab in one literal.
const cases = [
["word", "ab", 3, "ababab"],
["one", "abc", 1, "abc"],
["dash", "-", 5, "-----"],
["zero", "abc", 0, ""],
["empty", "", 5, ""],
["empty-zero", "", 0, ""],
["many", "ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab"],
["astral", "\u{1f642}", 3, "\u{1f642}\u{1f642}\u{1f642}"],
["combining", "e\u0301", 2, "e\u0301e\u0301"],
];
for (const [name, s, n, want] of cases) {
test(name, () => {
assert.equal(repeat(s, n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
// repeat returns n copies of s. String.prototype.repeat throws a RangeError
// if n is negative.
export function repeat(s: string, n: number): string {
return s.repeat(n);
}
repeat.test.ts 26 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { repeat } from "./repeat.ts";
// The case many has the 200 chars of 100 copies of ab in one literal.
const cases: [string, string, number, string][] = [
["word", "ab", 3, "ababab"],
["one", "abc", 1, "abc"],
["dash", "-", 5, "-----"],
["zero", "abc", 0, ""],
["empty", "", 5, ""],
["empty-zero", "", 0, ""],
["many", "ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab"],
["astral", "\u{1f642}", 3, "\u{1f642}\u{1f642}\u{1f642}"],
["combining", "e\u0301", 2, "e\u0301e\u0301"],
];
for (const [name, s, n, want] of cases) {
test(name, () => {
assert.equal(repeat(s, n), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
// Package repeat repeats a string.
package repeat
import "strings"
// Repeat returns n copies of s. strings.Repeat panics if n is negative.
func Repeat(s string, n int) string {
return strings.Repeat(s, n)
}
repeat_test.go 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
package repeat
import "testing"
// The case many has the 200 chars of 100 copies of ab in one literal.
var cases = []struct {
name, s string
n int
want string
}{
{"word", "ab", 3, "ababab"},
{"one", "abc", 1, "abc"},
{"dash", "-", 5, "-----"},
{"zero", "abc", 0, ""},
{"empty", "", 5, ""},
{"empty-zero", "", 0, ""},
{"many", "ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab"},
{"astral", "\U0001f642", 3, "\U0001f642\U0001f642\U0001f642"},
{"combining", "e\u0301", 2, "e\u0301e\u0301"},
}
func TestRepeat(t *testing.T) {
for _, c := range cases {
if got := Repeat(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/repeat-a-string/.
/// Returns n copies of s. str::repeat panics if the capacity overflows.
pub fn repeat(s: &str, n: usize) -> String {
s.repeat(n)
}
tests/repeat_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/repeat-a-string/.
use algo_repeat_a_string::repeat;
// The case many has the 200 chars of 100 copies of ab in one literal.
#[test]
fn cases() {
let cases: [(&str, &str, usize, &str); 9] = [
("word", "ab", 3, "ababab"),
("one", "abc", 1, "abc"),
("dash", "-", 5, "-----"),
("zero", "abc", 0, ""),
("empty", "", 5, ""),
("empty-zero", "", 0, ""),
("many", "ab", 100, "abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab"),
("astral", "\u{1f642}", 3, "\u{1f642}\u{1f642}\u{1f642}"),
("combining", "e\u{301}", 2, "e\u{301}e\u{301}"),
];
for (name, s, n, want) in cases {
assert_eq!(repeat(s, n), want, "{name}");
}
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/repeat-a-string/.
# repeat S N: prints N copies of S. A brace expansion such as {1..$n} does not
# expand the variable, so the function uses a loop.
repeat() {
local out='' i
for ((i = 0; i < $2; i++)); do
out+=$1
done
printf '%s' "$out"
}
test_repeat.bats 25 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/repeat-a-string/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/repeat.sh"
}
check() { # check S N WANT
run repeat "$1" "$2"
[ "$status" -eq 0 ]
[ "$output" = "$3" ]
}
# The case many has the 200 chars of 100 copies of ab in one string.
@test "word" { check 'ab' 3 'ababab'; }
@test "one" { check 'abc' 1 'abc'; }
@test "dash" { check '-' 5 '-----'; }
@test "zero" { check 'abc' 0 ''; }
@test "empty" { check '' 5 ''; }
@test "empty-zero" { check '' 0 ''; }
@test "many" { check 'ab' 100 'abababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababababab'; }
@test "astral" { check $'\xf0\x9f\x99\x82' 3 $'\xf0\x9f\x99\x82\xf0\x9f\x99\x82\xf0\x9f\x99\x82'; }
@test "combining" { check $'e\xcc\x81' 2 $'e\xcc\x81e\xcc\x81'; }
References
- The Python Standard Library, Built-in Types, Common Sequence Operations, note 2
- MDN Web Docs, String.prototype.repeat(), Exceptions, Examples
- Java SE 25 API, Class String, repeat(int)
- .NET API reference, Enumerable.Repeat method, Summary
- Go standard library, package strings, Repeat
- Rust standard library, primitive type str, repeat
- .NET API reference, String constructors, String(Char, Int32)
- cppreference.com, std::basic_string constructors, overload 3
- Bash Reference Manual, 3.5.1 Brace Expansion
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 HJPBMY Edit this page History Report an error Markdown