str_repeat

str_repeat(string $string, int $times): string

Repeats a string a given number of times.

C C23

C23
#include <stdio.h>
int main(void) {
    for (int i = 0; i < 3; i++) {
        fputs("ab", stdout); // C has no string-repeat function; print in a loop
    }
    putchar('\n');
    return 0;
}
Output
ababab

C++ C++26

C++26
#include <iostream>
#include <string>
int main() {
    std::string out;
    for (int i = 0; i < 3; i++) out += "ab";
    std::cout << out << "\n";
    return 0;
}
Output
ababab

C# v11.0.100

v11.0.100
Console.WriteLine(string.Concat(Enumerable.Repeat("ab", 3)));
Output
ababab

Go v1.27.4

v1.27.4
package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Repeat("ab", 3))
}
Output
ababab

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        System.out.println("ab".repeat(3));
    }
}
Output
ababab

JavaScript v26.13.1

v26.13.1
console.log("ab".repeat(3))
Output
ababab

PHP v8.6.0

v8.6.0
echo str_repeat("ab", 3);
Output
ababab

Python v3.15.2

v3.15.2
print("ab" * 3)
Output
ababab

Rust v1.99.1

v1.99.1
fn main() {
    println!("{}", "ab".repeat(3));
}
Output
ababab

TypeScript v26.13.1

v26.13.1
console.log("ab".repeat(3));
Output
ababab

Language differences

C: has no built-in containers or higher-order functions; the example loops fputs to emit the repetitions.

PHP: the built-in str_repeat; the other languages provide a repeat method or function.

Python: the * operator is the most concise (it also works on lists).

Rust: strings have a repeat method.