Repeat a string

From Rosetta Code

(Redirected from Repeating a string)
Jump to: navigation, search
Task
Repeat a string
You are encouraged to solve this task according to the task description, using any language you may know.
Take a string and repeat it some number of times. Example: repeat("ha", 5) => "hahahahaha"

If there is a simpler/more efficient way to repeat a single “character” (i.e. creating a string filled with a certain character), you might want to show that as well (i.e. repeat-char("*", 5) => "*****").

Contents

[edit] 4DOS Batch

gosub repeat ha 5
echo %@repeat[*,5]
quit
 
:Repeat [String Times]
do %Times%
echos %String%
enddo
echo.
return

Output shows:

hahahahaha
*****

[edit] ActionScript

ActionScript does not have a built-in way to repeat a string multiple times, but the addition operator can be used to concatenate strings.

[edit] Iterative version

function repeatString(string:String, numTimes:uint):String
{
var output:String = "";
for(var i:uint = 0; i < numTimes; i++)
output += string;
return output;
}

[edit] Recursive version

The following double-and-add method is much faster when repeating a string many times.

function repeatRecursive(string:String, numTimes:uint):String
{
if(numTimes == 0) return "";
if(numTimes & 1) return string + repeatRecursive(string, numTimes - 1);
var tmp:String = repeatRecursive(string, numTimes/2);
return tmp + tmp;
}

[edit] Ada

In Ada multiplication of an universal integer to string gives the desired result. Here is an example of use:

with Ada.Strings.Fixed;  use Ada.Strings.Fixed;
with Ada.Text_IO; use Ada.Text_IO;
 
procedure String_Multiplication is
begin
Put_Line (5 * "ha");
end String_Multiplication;

Sample output:

hahahahaha

[edit] ALGOL 68

print (5 * "ha")
 

[edit] AutoHotkey

MsgBox % Repeat("ha",5)
 
Repeat(String,Times)
{
Loop, %Times%
Output .= String
Return Output
}

[edit] Batch File

Commandline implementation

@echo off
if "%2" equ "" goto fail
setlocal enabledelayedexpansion
set char=%1
set num=%2
for /l %%i in (1,1,%num%) do set res=!res!% class="re2">char%
echo %res%
:fail

'Function' version

@echo off
setlocal enabledelayedexpansion
if "%2" equ "" goto fail
call :repeat %1 %2 res
echo %res%
goto :eof
 
:repeat
set char=%1
set num=%2
for /l %%i in (1,1,%num%) do set %3=!% class="re2">3!% class="re2">char%
goto :eof
 
:fail

[edit] Brainf***

+++++ +++++	init first as 10 counter
[-> +++++ +++++<] we add 10 to second each loopround
 
Now we want to loop 5 times to follow std
+++++
[-> ++++ . ----- -- . +++<] print h and a each loop
 
and a newline because I'm kind and it looks good
+++++ +++++ +++ . --- .

[edit] C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char * string_repeat( int n, const char * s ) {
size_t slen = strlen(s);
char * dest = calloc(n*slen+1, sizeof(char));
 
int i; char * p;
for ( i=0, p = dest; i < n; ++i, p += slen ) {
memcpy(p, s, slen);
}
return dest;
}
 
int main() {
printf("%s\n", string_repeat(5, "ha"));
return 0;
}

A variation.

...
char *string_repeat(char *str, int n)
{
char *pa, *pb;
size_t slen = strlen(str);
char *dest = malloc(n*slen+1);
 
pa = dest + (n-1)*slen;
strcpy(pa, str);
pb = --pa + slen;
while (pa>=dest) *pa-- = *pb--;
return dest;
}

To repeat a single character

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
char * char_repeat( int n, char c ) {
char * dest = calloc(n+1, sizeof(char));
memset(dest, c, n);
return dest;
}
 
int main() {
printf("%s\n", char_repeat(5, '*'));
return 0;
}

[edit] C++

#include <string>
#include <iostream>
 
std::string repeat( const std::string &word, int times ) {
std::string result ;
result.reserve(times*word.length()); // avoid repeated reallocation
for ( int a = 0 ; a < times ; a++ )
result += word ;
return result ;
}
 
int main( ) {
std::cout << repeat( "Ha" , 5 ) << std::endl ;
return 0 ;
}

To repeat a single character:

#include <string>
#include <iostream>
 
int main( ) {
std::cout << std::string( 5, '*' ) << std::endl ;
return 0 ;
}

[edit] C#

String s = "".PadLeft(5, 'X').Replace("X", "ha")

To repeat a single character:

String s = "".PadLeft(5, '*')

Or for a single character use the String(char, int) constructor:

String s = new String('*', 5);

[edit] Clojure

(apply str (repeat 5 "ha"))

[edit] Common Lisp

(defun repeat-string (n string)
(with-output-to-string (stream)
(loop repeat n do (write-string string stream))))
 
(princ (repeat-string 5 "hi"))

A single character may be repeated using just the builtin make-string:

(make-string 5 :initial-element #\X)

produces “XXXXX”.

[edit] D

Repeating a string:

import std.stdio;
import std.string;
 
void main()
{
writefln(repeat("ha", 5));
}

Repeating a character with vector operations:

import std.stdio;
 
void main() {
char[]str; // create the dynamic array
str.length = 5; // set the length
str[]='*'; // set all characters in the string to '*'
writefln(str);
}

[edit] E

"ha" * 5

[edit] Factor

: repeat-string ( str n -- str' ) swap <repetition> concat ;
 
"ha" 5 repeat-string print

[edit] Forth

: place-n { src len dest n -- }
0 dest c!
n 0 ?do src len dest +place loop ;
 
create test 256 allot
s" ha" test 5 place-n
test count type \ hahahahaha

The same code without the use of locals:

                                       ( src len dest n -- )
: place-n 0 over c! 0 ?do >r 2dup r@ +place r> loop drop 2drop ;
 
create test 256 allot
s" ha" test 5 place-n
test count type cr \ hahahahaha

Filling a string with a single character is supported by ANS-Forth:

create test 256 allot
 
test 10 char * fill \ repeat a single character
test 10 type

[edit] Fortran

Works with: Fortran version 90 and later

program test_repeat
 
write (*, '(a)') repeat ('ha', 5)
 
end program test_repeat

Output:

hahahahaha

[edit] Go

fmt.Println(strings.Repeat("ha", 5))  # ==> "hahahahaha"

"Characters" are just strings of length one.

[edit] Haskell

For a string of finite length:

concat $ replicate 5 "ha"

For an infinitely long string:

cycle "ha"

To repeat a single character:

replicate 5 '*'

[edit] HicEst

CHARACTER out*20
 
EDIT(Text=out, Insert="ha", DO=5)

[edit] Icon and Unicon

[edit] Icon

The procedure repl is a supplied function in Icon and Unicon.

procedure main(args)
write(repl(integer(!args) | 5))
end

If it weren't, one way to write it is:

procedure repl(s, n)
every (ns := "") ||:= |s\(0 <= n)
return ns
end

[edit] Unicon

This Icon solution works in Unicon.

[edit] J

   5 # '*'               NB. repeat each item 5 times
*****
5 # 'ha' NB. repeat each item 5 times
hhhhhaaaaa
(5 * # 'ha') $ 'ha' NB. repeat array 5 times (explicit)
hahahahaha
5 ((* #) $ ]) 'ha' NB. repeat array 5 times (tacit)
hahahahaha

[edit] Java

Works with: Java version 1.5+

There's no function or operator to do this in Java, so you have to do it yourself.

public static String repeat(String str, int times){
StringBuilder ret = new StringBuilder();
for(int i = 0;i < times;i++) ret.append(str);
return ret.toString();
}
 
public static void main(String[] args){
System.out.println(repeat("ha", 5));
}

Or even shorter:

public static String repeat(String str, int times){
return new String(new char[times]).replace("\0", str);
}

[edit] JavaScript

This solution creates an array of n+1 null elements, then joins them using the target string as the delimiter

String.prototype.repeat = function(n) {
return new Array(1 + parseInt(n, 10)).join(this);
}
 
alert("ha".repeat(5)); // hahahahaha

[edit] Liberty BASIC

a$ ="ha "
print StringRepeat$( a$, 5)
 
end
 
function StringRepeat$( in$, n)
o$ =""
for i =1 to n
o$ =o$ +in$
next i
StringRepeat$ =o$
end function

[edit] Logo

to copies :n :thing [:acc "||]
if :n = 0 [output :acc]
output (copies :n-1 :thing combine :acc :thing)
end

or using cascade:

show cascade 5 [combine "ha ?] "||    ; hahahahaha

[edit] Lua

function repeats(s, n) return n > 0 and s .. repeat(s, n-1) or "" end
 
Or use native string library function
string.rep(s,n)
 
 

[edit] MUMPS

 
RPTSTR(S,N)
 ;Repeat a string S for N times
NEW I
FOR I=1:1:N WRITE S
KILL I
QUIT
RPTSTR1(S,N) ;Functionally equivalent, but denser to read
F I=1:1:N W S
Q
 

[edit] OCaml

let string_repeat s n =
let len = String.length s in
let res = String.create(n * len) in
for i = 0 to pred n do
String.blit s 0 res (i * len) len;
done;
(res)
;;

testing in the toplevel:

# string_repeat "Hiuoa" 3 ;;
- : string = "HiuoaHiuoaHiuoa"

Alternately:

let string_repeat s n =
String.concat "" (Array.to_list (Array.make n s))
;;

Or:

let string_repeat s n =
Array.fold_left (^) "" (Array.make n s)
;;

To repeat a single character:

String.make 5 '*'

[edit] Oz

We have to write a function for this:

declare
fun {Repeat Xs N}
if N > 0 then
{Append Xs {Repeat Xs N-1}}
else
nil
end
end
in
{System.showInfo {Repeat "Ha" 5}}

[edit] Perl

"ha" x 5

[edit] Perl 6

Works with: Rakudo version #21 "Seattle"

"ha" x 5

(Note that the x operator isn't quite the same as in Perl 5: it now only creates strings. To create lists, use xx.)

[edit] PHP

str_repeat("ha", 5)

[edit] PicoLisp

(pack (need 5 NIL "ha"))
-> "hahahahaha"

or:

(pack (make (do 5 (link "ha"))))
-> "hahahahaha"

[edit] PL/I

 
s = copy('ha', 5);
 
/* To repeat a single character a fixed number of times: */
 
s = (5)(1)'h';
 

[edit] PostScript

% the comments show the stack content after the line was executed
% where rcount is the repeat count, "o" is for orignal,
% "f" is for final, and iter is the for loop variable
%
% usage: rcount ostring times -> fstring
 
/times {
dup length dup  % rcount ostring olength olength
4 3 roll  % ostring olength olength rcount
mul dup string  % ostring olength flength fstring
4 1 roll  % fstring ostring olength flength
1 sub 0 3 1 roll  % fstring ostring 0 olength flength_minus_one
{  % fstring ostring iter
1 index 3 index % fstring ostring iter ostring fstring
3 1 roll  % fstring ostring fstring iter ostring
putinterval  % fstring ostring
} for
pop  % fstring
} def

[edit] PowerBASIC

MSGBOX REPEAT$(5, "ha")

[edit] Prolog

 
%repeat(Str,Num,Res).
repeat(Str,1,Str).
repeat(Str,Num,Res):-
Num1 is Num-1,
repeat(Str,Num1,Res1),
string_concat(Str, Res1, Res).
 

[edit] Pure

str_repeat is defined by pattern-matching: repeating any string 0 times results in the empty string; while repeating it more than 0 times results in the concatenation of the string and (n-1) further repeats.

> str_repeat 0 s = "";
> str_repeat n s = s + (str_repeat (n-1) s) if n>0;
> str_repeat 5 "ha";
"hahahahaha"
>

[edit] PureBasic

Procedure.s RepeatString(count, text$=" ")
Protected i, ret$=""
 
For i = 1 To count
ret$ + text$
Next
ProcedureReturn ret$
EndProcedure
 
Debug RepeatString(5, "ha")

[edit] Python

"ha" * 5  # ==> "hahahahaha"

"Characters" are just strings of length one.

[edit] PowerShell

"ha" * 5  # ==> "hahahahaha"

[edit] R

paste(rep("ha",5), collapse='')

[edit] Ruby

"ha" * 5  # ==> "hahahahaha"

[edit] Scala

"ha" * 5 // ==> "hahahahaha"

[edit] Scheme

Works with: ?

(define (string-repeat n str)
(fold string-append "" (make-list n str)))
(string-repeat 5 "ha") ==> "hahahahaha"

To repeat a single character:

(make-string 5 #\*)

[edit] SNOBOL4

 
output = dupl("ha",5)
end
 

[edit] Suneido

'ha'.Repeat(5)  -->  "hahahahaha"
'*'.Repeat(5) --> "*****"

[edit] Tcl

string repeat "ha" 5  ;# => hahahahaha

[edit] Ursala

#import nat
 
repeat = ^|DlSL/~& iota
 
#cast %s
 
example = repeat('ha',5)

output:

'hahahahaha'

[edit] Visual Basic .NET

There is a simple instruction do repeat a char or a string the specified number of times (must be greater than 0).

String(5, "ha")
String(5, "*")

Those produces:

hahahahaha
*****
Personal tools