Repeat a string
You are encouraged to solve this task according to the task description, using any language you may know.
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) => "*****").
[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.
In Flex, there is the method mx.utils.StringUtil.repeat().
[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] Flex
import mx.utils.StringUtil;
trace(StringUtil.repeat("ha", 5));
Sample Output:
hahahahaha
[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] AppleScript
set str to "ha"
set final_string to ""
repeat 5 times
set final_string to final_string & str
end repeat
[edit] AutoHotkey
MsgBox % Repeat("ha",5)
Repeat(String,Times)
{
Loop, %Times%
Output .= String
Return Output
}
[edit] AWK
function repeat( str, n, rep, i )
{
for( ; i<n; i++ )
rep = rep str
return rep
}
BEGIN {
print repeat( "ha", 5 )
}
[edit] Babel
main: { "ha" 5 print_repeat }
print_repeat!: { <- { dup << } -> times }
Outputs:
hahahahaha
The '<<' operator prints, 'dup' duplicates the top-of-stack, 'times' does something x number of times. The arrows mean down (<-) and up (->) respectively - it would require a lengthy description to explain what this means, refer to the doc/babel_ref.txt file in the github repo linked from Babel
[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!%char%
echo %res%
:fail
'Function' version
@echo off
set /p a=Enter string to repeat :
set /p b=Enter how many times to repeat :
set "c=1"
set "d=%b%"
:a
echo %a%
set "c=%c%+=1"
if /i _"%c%"==_"%d%" (exit /b)
goto :a
'Function' version 2
@echo off
@FOR /L %%i in (0,1,9) DO @CALL :REPEAT %%i
@echo That's it!
@FOR /L %%i in (0,1,9) DO @CALL :REPEAT %%i
@echo.
@echo And that!
@GOTO END
:REPEAT
@echo|set /p="*"
@GOTO:EOF
:END
[edit] BBC BASIC
PRINT STRING$(5, "ha")
[edit] Bracmat
The code almost explains itself. The repetions are accumulated in a list rep. The str concatenates all elements into a single string, ignoring the white spaces separating the elements.
(repeat=
string N rep
. !arg:(?string.?N)
& !string:?rep
& whl
' (!N+-1:>0:?N&!string !rep:?rep)
& str$!rep
);
repeat$(ha.5) hahahahaha
[edit] Brainf***
Prints "ha" 10 times. Note that this method only works for a number of repetitions that fit into the cell size.
+++++ +++++ 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] Brat
p "ha" * 5 #Prints "hahahahaha"
[edit] Burlesque
blsq ) 'h5?*
"hhhhh"
blsq ) "ha"5.*\[
"hahahahaha"
[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 = malloc(n*slen+1);
int i; char * p;
for ( i=0, p = dest; i < n; ++i, p += slen ) {
memcpy(p, s, slen);
}
*p = '\0';
return dest;
}
int main() {
char * result = string_repeat(5, "ha")
puts(result);
free(result);
return 0;
}
A variation.
...
char *string_repeat(const 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 = malloc(n+1);
memset(dest, c, n);
dest[n] = '\0';
return dest;
}
int main() {
char * result = char_repeat(5, '*');
puts(result);
free(result);
return 0;
}
If you use GLib, simply use g_strnfill ( gsize length, gchar fill_char ) function.
[edit] C#
string s = "".PadLeft(5, 'X').Replace("X", "ha");
or (with .NET 2+)
string s = new String('X', 5).Replace("X", "ha");
or (with .NET 2+)
string s = String.Join("ha", new string[5 + 1]);
or (with .NET 4+)
string s = String.Concat(Enumerable.Repeat("ha", 5));
To repeat a single character:
string s = "".PadLeft(5, '*');
or (with .NET 2+)
string s = new String('*', 5);
[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] 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, std.array;
void main() {
writeln("ha".replicate(5));
}
Repeating a character with vector operations:
import std.stdio;
void main() {
char[] chars; // create the dynamic array
chars.length = 5; // set the length
chars[] = '*'; // set all characters in the string to '*'
writeln(chars);
}
[edit] Delphi
Repeat a string
function RepeatString(const s: string; count: cardinal): string;
var
i: Integer;
begin
for i := 1 to count do
Result := Result + s;
end;
Writeln(RepeatString('ha',5));
Repeat a character
Writeln( StringOfChar('a',5) );
Built in RTL function:
StrUtils.DupeString
[edit] DWScript
Repeat a string
PrintLn( StringOfString('abc',5) );
Repeat a character
PrintLn( StringOfChar('a',5) );
[edit] E
"ha" * 5
[edit] Erlang
repeat(X,N) ->
lists:flatten(lists:duplicate(N,X)).
This will duplicate a string or character N times to produce a new string.
[edit] Euphoria
function repeat_string(object x, integer times)
sequence out
if atom(x) then
return repeat(x,times)
else
out = ""
for n = 1 to times do
out &= x
end for
return out
end if
end function
puts(1,repeat_string("ha",5) & '\n') -- hahahahaha
puts(1,repeat_string('*',5) & '\n') -- *****
Sample Output:
hahahahaha *****
-- Here is an alternative method for "Repeat a string"
include std/sequence.e
printf(1,"Here is the repeated string: %s\n", {repeat_pattern("ha",5)})
printf(1,"Here is another: %s\n", {repeat_pattern("*",5)})
Sample Output:
Here is the repeated string: hahahahaha Here is another: *****
[edit] F#
> String.replicate 5 "ha";;
val it : string = "hahahahaha"
Or
> String.Concat( Array.create 5 "ha" );;
val it : string = "hahahahaha"
[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 ;
s" ha" pad 5 place-n
pad count type \ hahahahaha
The same code without the use of locals:
: place-n ( src len dest n -- )
swap >r 0 r@ c!
begin dup while -rot 2dup r@ +place rot 1- repeat
r> 2drop 2drop ;
s" ha" pad 5 place-n
pad count type \ hahahahaha
Filling a string with a single character is supported by ANS-Forth:
pad 10 char * fill \ repeat a single character
pad 10 type \ **********
[edit] Fortran
program test_repeat
write (*, '(a)') repeat ('ha', 5)
end program test_repeat
Output:
hahahahaha
[edit] Frink
println[repeat["ha", 5]]
[edit] GAP
Concatenation(List([1 .. 10], n -> "BOB "));
# "BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "
[edit] Go
fmt.Println(strings.Repeat("ha", 5)) // ==> "hahahahaha"
There is no special way to repeat a single character, other than to convert the character to a string. The following works:
fmt.Println(strings.Repeat(string('h'), 5)) // prints hhhhh
[edit] Groovy
println 'ha' * 5
[edit] Haskell
For a string of finite length:
concat $ replicate 5 "ha"
Or with list-monad (a bit obscure):
[1..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
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] Inform 7
Home is a room.
To decide which indexed text is (T - indexed text) repeated (N - number) times:
let temp be indexed text;
repeat with M running from 1 to N:
let temp be "[temp][T]";
decide on temp.
When play begins:
say "ha" repeated 5 times;
end the story.
[edit] J
5 # '*' NB. repeat each item 5 times
*****
5 # 'ha' NB. repeat each item 5 times
hhhhhaaaaa
5 ((* #) $ ]) 'ha' NB. repeat array 5 times
hahahahaha
5 ;@# < 'ha' NB. boxing is used to treat the array as a whole
hahahahaha
[edit] Java
There's no method 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);
}
In Apache Commons Lang, there is a StringUtils.repeat() method.
[edit] JavaScript
This solution creates an empty array of length n+1, then uses the array's join method to effectively concatenate the string n times. Note that extending the prototype of built-in objects is not a good idea if the code is to run in a shared workspace.
String.prototype.repeat = function(n) {
return new Array(1 + n).join(this);
}
alert("ha".repeat(5)); // hahahahaha
[edit] Julia
"ha"^5
'*'^5
#the (^) operator is really just call to the `repeat` function
repeat("ha",5)
[edit] K
,/5#,"ha"
"hahahahaha"
5#"*"
"*****"
[edit] LabVIEW
I don't know if there is a built-in function for this, but it is easily achieved with a For loop and Concatenate Strings.
[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
Lhogho doesn't have cascade (yet), nor does it have the initialise a missing parameter capability demonstrated by the [:acc "||] above.
to copies :n :thing :acc
if :n = 0 [output :acc]
output (copies :n-1 :thing combine :acc :thing)
end
print copies 5 "ha "||
[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] Maple
There are many ways to do this in Maple. First, the "right" (most efficient) way is to use the supplied procedures for this purpose.
> use StringTools in
> Repeat( "abc", 10 ); # repeat an arbitrary string
> Fill( "x", 20 ) # repeat a character
> end use;
"abcabcabcabcabcabcabcabcabcabc"
"xxxxxxxxxxxxxxxxxxxx"
These next two are essentially the same, but are less efficient (though still linear) because they create a sequence of 10 strings before concatenating them (with the built-in procedure cat) to form the result.
> cat( "abc" $ 10 );
"abcabcabcabcabcabcabcabcabcabc"
> cat( seq( "abc", i = 1 .. 10 ) );
"abcabcabcabcabcabcabcabcabcabc"
You can build up a string in a loop, but this is highly inefficient (quadratic); don't do this.
> s := "":
> to 10 do s := cat( s, "abc" ) end: s;
"abcabcabcabcabcabcabcabcabcabc"
If you need to build up a string incrementally, use a StringBuffer object, which keeps things linear.
Finally, note that strings and characters are not distinct datatypes in Maple; a character is just a string of length one.
[edit] Mathematica
(* solution 1 *)
rep[n_Integer,s_String]:=Apply[StringJoin,ConstantArray[s,{n}]]
(* solution 2 -- @@ is the infix form of Apply[] *)
rep[n_Integer,s_String]:=StringJoin@@Table[s,{n}]
(* solution 3 -- demonstrating another of the large number of looping constructs available *)
rep[n_Integer,s_String]:=Nest[StringJoin[s, #] &,s,n-1]
[edit] MATLAB / Octave
function S = repeat(s , n)
S = repmat(s , [1,n]) ;
return
Note 1: The repetition is returned, not displayed.
Note 2: To repeat a string, use single quotes. Example: S=repeat('ha',5)
[edit] Maxima
"$*"(s, n) := apply(sconcat, makelist(s, n))$
infix("$*")$
"abc" $* 5;
/* "abcabcabcabcabc" */
[edit] Mercury
Mercury's 'string' module provides an efficient char-repeater. The following uses string.builder to repeat strings.
:- module repeat.
:- interface.
:- import_module string, char, int.
:- func repeat_char(char, int) = string.
:- func repeat(string, int) = string.
:- implementation.
:- import_module stream, stream.string_writer, string.builder.
repeat_char(C, N) = string.duplicate_char(C, N).
repeat(String, Count) = Repeated :-
S0 = string.builder.init,
Repeated = string.builder.to_string(S),
printn(string.builder.handle, Count, String, S0, S).
:- pred printn(Stream, int, string, State, State)
<= (stream.writer(Stream, string, State),
stream.writer(Stream, character, State)).
:- mode printn(in, in, in, di, uo) is det.
printn(Stream, N, String, !S) :-
( N > 0 ->
print(Stream, String, !S),
printn(Stream, N - 1, String, !S)
; true ).
[edit] Mirah
x = StringBuilder.new
5.times do
x.append "ha"
end
puts x # ==> "hahahahaha"
[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
This last example uses the $PIECE function.
;Even better (more terse)
S x="",$P(x,"-",10)="-"
W x
[edit] NetRexx
NetRexx has built in functions to manipulate strings. The most appropriate for this task is the copies() function:
/* NetRexx */
ha5 = 'ha'.copies(5)
There are several other built-in functions that can be used to achieve the same result depending on need:
/* NetRexx */
sampleStr = 'ha' -- string to duplicate
say ' COPIES:' sampleStr.copies(5)
say 'CHANGESTR:' '.....'.changestr('.', sampleStr)
sampleChr = '*' -- character to duplicate
say ' LEFT:' sampleChr.left(5, sampleChr)
say ' RIGHT:' sampleChr.right(5, sampleChr)
say ' CENTRE:' sampleChr.centre(5, sampleChr)
say ' OVERLAY:' sampleChr.overlay(sampleChr, 1, 5, sampleChr)
say ' SUBSTR:' ''.substr(1, 5, sampleChr)
say 'TRANSLATE:' '.....'.translate(sampleChr, '.')
[edit] NewLISP
(dup "ha" 5)
[edit] Objeck
bundle Default {
class Repeat {
function : Main(args : String[]) ~ Nil {
Repeat("ha", 5)->PrintLine();
}
function : Repeat(string : String, max : Int) ~ String {
repeat : String := String->New();
for(i := 0; i < max; i += 1;) {
repeat->Append(string);
};
return repeat;
}
}
}
[edit] Objective-C
Objective-C allows developers to extend existing an existing class by adding additional methods to the class without needing to subclass. These extensions are called categories. Category methods are available to all instances of the class, as well as any instances of its subclasses.
This task provides us with an opportunity to visit this aspect of the language feature.
We will extend NSString, the de facto Objective-C string class in environments that are either compatible with or descend directly from the OPENSTEP specification, such as GNUstep and Mac OS X, respectively, with a method that accomplishes the described task.
@interface NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times;
@end
@implementation NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times {
return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];
}
@end
Now, let's put it to use:
// Instantiate an NSString by sending an NSString literal our new
// -repeatByNumberOfTimes: selector.
NSString *aString = [@"ha" repeatStringByNumberOfTimes:5];
// Display the NSString.
NSLog(@"%@", aString);
[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] OpenEdge/Progress
MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.
[edit] OxygenBasic
'REPEATING A CHARACTER
print string 10,"A" 'result AAAAAAAAAA
'REPEATING A STRING
function RepeatString(string s,sys n) as string
sys i, le=len s
if le=0 then exit function
n*=le
function=nuls n
'
for i=1 to n step le
mid function,i,s
next
end function
print RepeatString "ABC",3 'result ABCABCABC
[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] PARI/GP
This solution is unimaginably bad. Slightly less bad versions can be designed, but that's not the point: don't use GP for text processing if you can avoid it. If you really need to, it's easy to create an efficient function in PARI (see C) and pass that to GP.
repeat(s,n)={
if(n, Str(repeat(s, n-1), s), "")
};
[edit] Pascal
See Delphi
[edit] Perl
"ha" x 5
[edit] Perl 6
"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 "ha"))
-> "hahahahaha"
or:
(pack (make (do 5 (link "ha"))))
-> "hahahahaha"
[edit] Pike
"ha"*5;
[edit] PL/I
s = copy('ha', 5);
/* To repeat a single character a fixed number of times: */
s = (5)'h'; /* asigns 'hhhhh' to s. */
[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] PowerShell
"ha" * 5 # ==> "hahahahaha"
[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.
the other way also works:
5 * "ha" # ==> "hahahahaha"
[edit] R
paste(rep("ha",5), collapse='')
[edit] Racket
#lang racket
;; fast
(define (string-repeat n str)
(string-append* (make-list n str)))
(string-repeat 5 "ha") ; => "hahahahaha"
To repeat a single character:
(make-string 5 #\*) => "*****"
[edit] REALbasic
Function Repeat(s As String, count As Integer) As String
Dim output As String
For i As Integer = 0 To count
output = output + s
Next
Return output
End Function
[edit] REBOL
head insert/dup "" "ha" 5
[edit] Retro
with strings'
: repeatString ( $n-$ )
1- [ dup ] dip [ over prepend ] times nip ;
"ha" 5 repeatString
[edit] REXX
Since the REXX language only supports the "character" type, it's not surprising that there are so many ways to skin a cat.
/*REXX program to show various ways to repeat a string (or repeat a single char).*/
/*all examples are equivalent, but not created equal.*/
/*───────────────────────────────────────────*/
y='ha'
z=copies(y,5)
/*───────────────────────────────────────────*/
z=copies( 'ha', 5 )
/*───────────────────────────────────────────*/
y='ha'
z=y||y||y||y||y
/*───────────────────────────────────────────*/
y='ha'
z=y || y || y || y || y /*same as previous, but the "big sky" version*/
/*───────────────────────────────────────────*/
y='ha'
z=''
do 5
z=z||y
end
/*───────────────────────────────────────────*/
y="ha"
z=
do 5
z=z||y
end
/*───────────────────────────────────────────*/
y="ha"
z=
do i=101 to 105
z=z||y
end
/*───────────────────────────────────────────*/
y='+'
z=left('',5,y)
/*───────────────────────────────────────────*/
y='+'
z=right('',5,y)
/*───────────────────────────────────────────*/
y='+'
z=substr('',1,5,y)
/*───────────────────────────────────────────*/
y='+'
z=center('',5,y)
/*───────────────────────────────────────────*/
y='+'
z=centre('',5,y)
/*───────────────────────────────────────────*/
y='+'
z=space('',5,y)
/*───────────────────────────────────────────*/
y='+'
z=translate('@@@@@',y,"@")
/*───────────────────────────────────────────*/
y='abcdef'
z=five(y)
exit
five: procedure expose y; parse arg g
if length(g)>=5*length(y) then return g
return five(y||g)
/*───────────────────────────────────────────*/
y='something wicked this way comes.'
z=y||y||y||y||y||y||y||y||y||y||y||y|\y||y||y
z=left(z,5*length(y))
/*───────────────────────────────────────────*/
y='+'
z=copies('',5,y)
/*───────────────────────────────────────────*/
y='+'
z=lower('',1,5,y)
/*───────────────────────────────────────────*/
y='+'
z=lower('',,5,y)
/*───────────────────────────────────────────*/
z='+'
z=upper('',1,5,y)
/*───────────────────────────────────────────*/
z=upper('',,5,y)
/*───────────────────────────────────────────*/
y='charter bus.'
z='*****'
z=changestr('*',z,y)
/*───────────────────────────────────────────*/
y='what the hey!'
z=
do until length(z)==5*length(y)
z=z||y
end
/*───────────────────────────────────────────*/
y='what the hey!'
z=
do until length(z)==5*length(y)
z=insert(z,0,y)
end
/*───────────────────────────────────────────*/
y='yippie ki yay'
z=
do i=1 by 5 for 5
z=overlay(y,z,i)
end
/*───────────────────────────────────────────*/
y='+'
z=justify('',5,y)
/*───────────────────────────────────────────*/
whatever_this_variable_is_____it_aint_referenced_directly= 'boy oh boy.'
z=; signal me; me:
do 5
z=z||strip(subword(sourceline(sigl-1),2),,"'")
end
/*───────────────────────────────────────────*/
y="any more examples & the angry townfolk with pitchforks will burn the castle."
parse value y||y||y||y||y with z
exit /*stick a fork in it, we're done.*/
Some older REXXes don't have a changestr bif, so one is included here ──► CHANGESTR.REX.
[edit] Ruby
"ha" * 5 # ==> "hahahahaha"
Despite the use of the * operator, the operation is not commutative:
5 * "ha" # TypeError: String can't be coerced into Fixnum
[edit] Run BASIC
a$ = "ha "
for i = 1 to 5
a1$ = a1$ + a$
next i
a$ = a1$
print a$
[edit] Scala
"ha" * 5 // ==> "hahahahaha"
[edit] Scheme
(define (string-repeat n str)
(apply string-append (vector->list (make-vector n str))))
with SRFI 1:
(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] Scratch
This example requires making variables named "String", "Count", and "Repeated" first.
[edit] sed
Number of ampersands indicates number of repetitions.
$ echo ha | sed 's/.*/&&&&&/'
hahahahaha
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
begin
writeln("ha" mult 5);
end func;
Output:
hahahahaha
[edit] Smalltalk
If n is a small constant, then simply concatenating n times will do; for example, n=5::
v := 'ha'.
v,v,v,v,v
By creating a collection of n 'ha', and joining them to a string:
((1 to: n) collect: [:x | 'ha']) joinUsing: ''.or:
(Array new:n withAll:'ha') asStringWith:''.
By creating a WriteStream, and putting N times the string 'ha' into it:
ws := '' writeStream.
n timesRepeat: [ws nextPutAll: 'ha'].
ws contents.
alternatively:
(String streamContents:[:ws | n timesRepeat: [ws nextPutAll: 'ha']])
all evaluate to:
hahahahaha
A string containing a repeated character is generated with:
String new:n withAll:$*
[edit] SNOBOL4
output = dupl("ha",5)
end
[edit] SQL
SELECT rpad('', 10, 'ha')
[edit] Standard ML
fun string_repeat (s, n) =
concat (List.tabulate (n, fn _ => s))
;
testing in the interpreter:
- string_repeat ("Hiuoa", 3) ;
val it = "HiuoaHiuoaHiuoa" : string
To repeat a single character:
fun char_repeat (c, n) =
implode (List.tabulate (n, fn _ => c))
;
[edit] Suneido
'ha'.Repeat(5) --> "hahahahaha"
'*'.Repeat(5) --> "*****"
[edit] Tcl
string repeat "ha" 5 ;# => hahahahaha
[edit] TUSCRIPT
$$ MODE TUSCRIPT
repeatstring=REPEAT ("ha",5)
[edit] TorqueScript
--Eepos
function strRep(%str,%int)
{
for(%i = 0; %i < %int; %i++)
{
%rstr = %rstr@%str;
}
return %rstr;
}
[edit] UNIX Shell
[edit] Using printf
printf "ha"%.0s {1..5}
With ksh93 and zsh, the count can vary.
i=5
printf "ha"%.0s {1..$i}
With bash, {1..$i} fails, because brace expansion happens before variable substitution. The fix uses eval.
i=5
eval "printf 'ha'%.0s {1..$i}"
For the general case, one must escape any % or \ characters in the string, because printf would interpret those characters.
reprint() {
typeset e="$(sed -e 's,%,%%,g' -e 's,\\,\\\\,g' <<<"$1")"
eval 'printf "$e"%.0s '"{1..$2}"
}
reprint '% ha \' 5
[edit] Using head -c
head -c is a GNU extension, so it only works with those systems. (Also, this script can only repeat a single character.)
width=72; char='='
head -c ${width} < /dev/zero | tr '\0' "$char"
[edit] Ursala
#import nat
repeat = ^|DlSL/~& iota
#cast %s
example = repeat('ha',5)
output:
'hahahahaha'
[edit] Vala
Repeat a string 5 times:
string s = "ha";
string copy = "";
for (int x = 0; x < 5; x++)
copy += s;
Fill a string with a char N times:
string s = string.nfill(5, 'c');
[edit] VBA
Public Function RepeatStr(aString As String, aNumber As Integer) As String
Dim bString As String
bString = aString
If aNumber > 1 Then
For i = 2 To aNumber
bString = bString & aString
Next i
End If
RepeatStr = bString
End Function
Sample output:
print RepeatSTr( "Hello world!", 3) Hello world!Hello world!Hello world!
Note: unlike Visual Basic .NET, "String(5, "ha") in VBA produces "hhhhh" (only the first character is repeated)!
[edit] Vedit macro language
Ins_Text("ha", COUNT, 5)
[edit] Visual Basic .NET
Use the PadLeft & PadRight commands:
FileContents = "X".PadRight(FileSizeBytes - 1, "X")
Where:
* FileContents is the string to populate
* FileSizeBytes is the number of repetitions (Remember that "-1" is valid as we have already specified the first character as being "X", which is to be padded on.
This produces:
"XXXXXXXXXX...........XXXXXXXXX"
[edit] XPL0
cod T=12; int I; for I gets 1,5 do T(0,"ha")
- Output:
hahahahaha
[edit] Yorick
array("ha", 5)(sum)
- Programming Tasks
- String manipulation
- 4DOS Batch
- ActionScript
- Ada
- ALGOL 68
- AppleScript
- AutoHotkey
- AWK
- Babel
- Batch File
- BBC BASIC
- Bracmat
- Brainf***
- Brat
- Burlesque
- C
- C sharp
- C++
- Clojure
- Common Lisp
- D
- Delphi
- DWScript
- E
- Erlang
- Euphoria
- F Sharp
- Factor
- Forth
- Fortran
- Frink
- GAP
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- Inform 7
- J
- Java
- JavaScript
- Julia
- K
- LabVIEW
- Liberty BASIC
- Logo
- Lua
- Maple
- Mathematica
- MATLAB
- Octave
- Maxima
- Mercury
- Mirah
- MUMPS
- NetRexx
- NewLISP
- Objeck
- Objective-C
- OCaml
- OpenEdge/Progress
- OxygenBasic
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pike
- PL/I
- PostScript
- PowerBASIC
- PowerShell
- Prolog
- Pure
- PureBasic
- Python
- R
- Racket
- REALbasic
- REBOL
- Retro
- REXX
- Ruby
- Run BASIC
- Scala
- Scheme
- Scratch
- Sed
- Seed7
- Smalltalk
- SNOBOL4
- SQL
- Standard ML
- Suneido
- Tcl
- TUSCRIPT
- TorqueScript
- UNIX Shell
- Ursala
- Vala
- VBA
- Vedit macro language
- Visual Basic .NET
- XPL0
- Yorick
