Repeat a string: Difference between revisions
m →{{header|Python}}: output comments |
PascalABC.NET |
||
(78 intermediate revisions by 46 users not shown) | |||
Line 6: | Line 6: | ||
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) => "*****"). |
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) => "*****"). |
||
{{Template:Strings}} |
|||
<br><br> |
<br><br> |
||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">print(‘ha’ * 5)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hahahahaha |
|||
</pre> |
|||
=={{header|360 Assembly}}== |
|||
<syntaxhighlight lang="360asm">* Repeat a string - 19/04/2020 |
|||
REPEATS CSECT |
|||
USING REPEATS,R13 base register |
|||
B 72(R15) skip savearea |
|||
DC 17F'0' savearea |
|||
SAVE (14,12) save previous context |
|||
ST R13,4(R15) link backward |
|||
ST R15,8(R13) link forward |
|||
LR R13,R15 set addressability |
|||
XPRNT C24,24 print c24 |
|||
LA R1,PARMLST pg=repeat(cx,ii) - repeat('abc ',6) |
|||
BAL R14,REPEAT call repeat |
|||
XPRNT PG,L'PG print pg |
|||
L R13,4(0,R13) restore previous savearea pointer |
|||
RETURN (14,12),RC=0 restore registers from calling save |
|||
REPEAT CNOP 0,4 procedure repeat(b,a,i) |
|||
STM R2,R8,REPEATSA save registers |
|||
L R2,0(R1) @b=%r1 |
|||
L R3,4(R1) @a=%(r1+4) |
|||
L R4,8(R1) @i=%(r1+8) |
|||
LR R5,R3 length(a) before a |
|||
SH R5,=H'2' @lengh(a) |
|||
LH R6,0(R5) l=length(a) |
|||
LR R7,R6 l |
|||
BCTR R7,0 l-1 |
|||
L R8,0(R4) i=%r4 |
|||
LTR R8,R8 if i<=0 |
|||
BNP RET then return |
|||
LOOP EX R7,MVCX move a to b len R6 |
|||
AR R2,R6 @b+=l |
|||
BCT R8,LOOP loop i times |
|||
RET LM R2,R8,REPEATSA restore registers |
|||
BR R14 return |
|||
PARMLST DC A(PG,CX,II) parmlist |
|||
REPEATSA DS 7F local savearea |
|||
MVCX MVC 0(0,R2),0(R3) move @ R3 to @ R2 |
|||
C24 DC 6C'xyz ' constant repeat - repeat('xyz ',6) |
|||
LCX DC AL2(L'CX) lengh(cc) |
|||
CX DC CL4'abc ' cx |
|||
II DC F'6' ii |
|||
PG DC CL80' ' pg |
|||
REGEQU |
|||
END REPEATS </syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
xyz xyz xyz xyz xyz xyz |
|||
abc abc abc abc abc abc |
|||
</pre> |
|||
=={{header|4DOS Batch}}== |
=={{header|4DOS Batch}}== |
||
< |
<syntaxhighlight lang="4dos">gosub repeat ha 5 |
||
echo %@repeat[*,5] |
echo %@repeat[*,5] |
||
quit |
quit |
||
Line 18: | Line 79: | ||
enddo |
enddo |
||
echo. |
echo. |
||
return</ |
return</syntaxhighlight> |
||
Output shows: |
Output shows: |
||
<pre>hahahahaha |
<pre>hahahahaha |
||
*****</pre> |
*****</pre> |
||
=={{header|6502 Assembly}}== |
|||
<syntaxhighlight lang="6502asm">CHROUT equ $FFD2 ;KERNAL call, prints the accumulator to the screen as an ascii value. |
|||
org $0801 |
|||
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00 |
|||
lda #>TestStr |
|||
sta $11 |
|||
lda #<TestStr |
|||
sta $10 |
|||
ldx #5 ;number of times to repeat |
|||
loop: |
|||
jsr PrintString |
|||
dex |
|||
bne loop |
|||
RTS ;RETURN TO BASIC |
|||
PrintString: |
|||
ldy #0 |
|||
loop_PrintString: |
|||
lda ($10),y ;this doesn't actually increment the pointer itself, so we don't need to back it up. |
|||
beq donePrinting |
|||
jsr CHROUT |
|||
iny |
|||
jmp loop_PrintString |
|||
donePrinting: |
|||
rts |
|||
TestStr: |
|||
db "HA",0</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
READY. |
|||
LOAD"*",8,1: |
|||
SEARCHING FOR * |
|||
LOADING |
|||
READY. |
|||
RUN |
|||
HAHAHAHAHA |
|||
READY. |
|||
</pre> |
|||
=={{header|68000 Assembly}}== |
|||
Easiest way to do this is with a loop. |
|||
<syntaxhighlight lang="68000devpac">MOVE.W #5-1,D1 |
|||
RepString: |
|||
LEA A3, MyString |
|||
MOVE.L A3,-(SP) ;PUSH A3 |
|||
JSR PrintString ;unimplemented hardware-dependent printing routine, assumed to not clobber D1 |
|||
MOVE.L (SP)+,A3 ;POP A3 |
|||
DBRA D1,RepString |
|||
RTS ;return to basic or whatever |
|||
MyString: |
|||
DC.B "ha",0 |
|||
even</syntaxhighlight> |
|||
=={{header|8080 Assembly}}== |
|||
<syntaxhighlight lang="asm8080"> org 100h |
|||
jmp demo |
|||
; Repeat the string at DE into HL, B times |
|||
repeat: mvi c,'$' ; string terminator |
|||
xra a ; repeat 0x? |
|||
ora b |
|||
mov m,c ; then empty string |
|||
rz |
|||
rpt1: push d ; save begin of string to repeat |
|||
chcpy: ldax d ; copy character from input to output |
|||
mov m,a |
|||
inx d ; advance pointers |
|||
inx h |
|||
cmp c ; end of string? |
|||
jnz chcpy |
|||
pop d ; restore begin of string to repeat |
|||
dcx h ; move back past terminator in copy |
|||
dcr b ; done yet? |
|||
jnz rpt1 ; if not add another copy |
|||
ret |
|||
demo: lxi d,ha ; get string to repeat |
|||
lxi h,buf ; place to store result |
|||
mvi b,5 ; repeat 5 times |
|||
call repeat |
|||
lxi d,buf ; print result using CP/M call |
|||
mvi c,9 |
|||
jmp 5 |
|||
ha: db 'ha$' ; string to repeat |
|||
buf: ds 32 ; place to store repeated string</syntaxhighlight> |
|||
{{out}} |
|||
<pre>hahahahaha</pre> |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth">"ha" 5 s:* |
||
. cr</ |
. cr</syntaxhighlight> |
||
Output shows: |
Output shows: |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
Line 32: | Line 200: | ||
This works for ABAP Version 7.40 and above |
This works for ABAP Version 7.40 and above |
||
<syntaxhighlight lang="abap"> |
|||
<lang ABAP> |
|||
report z_repeat_string. |
report z_repeat_string. |
||
write repeat( val = `ha` occ = 5 ). |
write repeat( val = `ha` occ = 5 ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
hahahahaha |
hahahahaha |
||
</pre> |
</pre> |
||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">Proc Main() |
|||
byte REPEAT |
|||
REPEAT=5 |
|||
Do |
|||
Print("ha") |
|||
REPEAT==-1 |
|||
Until REPEAT=0 |
|||
Do |
|||
Return</syntaxhighlight> |
|||
{{out}} |
|||
<pre>hahahahaha</pre> |
|||
=={{header|ActionScript}}== |
=={{header|ActionScript}}== |
||
Line 50: | Line 232: | ||
===Iterative version=== |
===Iterative version=== |
||
< |
<syntaxhighlight lang="actionscript">function repeatString(string:String, numTimes:uint):String |
||
{ |
{ |
||
var output:String = ""; |
var output:String = ""; |
||
Line 56: | Line 238: | ||
output += string; |
output += string; |
||
return output; |
return output; |
||
}</ |
}</syntaxhighlight> |
||
===Recursive version=== |
===Recursive version=== |
||
The following double-and-add method is much faster when repeating a string many times. |
The following double-and-add method is much faster when repeating a string many times. |
||
< |
<syntaxhighlight lang="actionscript">function repeatRecursive(string:String, numTimes:uint):String |
||
{ |
{ |
||
if(numTimes == 0) return ""; |
if(numTimes == 0) return ""; |
||
Line 66: | Line 248: | ||
var tmp:String = repeatRecursive(string, numTimes/2); |
var tmp:String = repeatRecursive(string, numTimes/2); |
||
return tmp + tmp; |
return tmp + tmp; |
||
}</ |
}</syntaxhighlight> |
||
===Flex=== |
===Flex=== |
||
< |
<syntaxhighlight lang="actionscript">import mx.utils.StringUtil; |
||
trace(StringUtil.repeat("ha", 5)); |
trace(StringUtil.repeat("ha", 5)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample Output: |
Sample Output: |
||
<pre> |
<pre> |
||
Line 79: | Line 261: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
In [[Ada]] multiplication of an universal integer to string gives the desired result. Here is an example of use: |
In [[Ada]] multiplication of an universal integer to string gives the desired result. Here is an example of use: |
||
< |
<syntaxhighlight lang="ada">with Ada.Strings.Fixed; use Ada.Strings.Fixed; |
||
with Ada.Text_IO; use Ada.Text_IO; |
with Ada.Text_IO; use Ada.Text_IO; |
||
Line 85: | Line 267: | ||
begin |
begin |
||
Put_Line (5 * "ha"); |
Put_Line (5 * "ha"); |
||
end String_Multiplication;</ |
end String_Multiplication;</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 92: | Line 274: | ||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
< |
<syntaxhighlight lang="aime">call_n(5, o_text, "ha");</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
< |
<syntaxhighlight lang="algol68">print (5 * "ha") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Amazing Hopper}}== |
|||
<syntaxhighlight lang="amazing hopper"> |
|||
#!/usr/bin/hopper |
|||
#include <hopper.h> |
|||
main: |
|||
{"ha"}replyby(5), println |
|||
{"ha",5}replicate, println |
|||
{0}return |
|||
</syntaxhighlight> |
|||
hahahahaha |
|||
hahahahaha |
|||
=={{header|APL}}== |
=={{header|APL}}== |
||
Fill up a string of length 10 with 'ha': |
Fill up a string of length 10 with 'ha': |
||
< |
<syntaxhighlight lang="apl"> 10⍴'ha' |
||
hahahahaha</ |
hahahahaha</syntaxhighlight> |
||
Alternatively, define a function: |
Alternatively, define a function: |
||
< |
<syntaxhighlight lang="apl"> REPEAT←{(⍺×⍴⍵)⍴⍵} |
||
5 REPEAT 'ha' |
5 REPEAT 'ha' |
||
hahahahaha</ |
hahahahaha</syntaxhighlight> |
||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">set str to "ha" |
||
set final_string to "" |
set final_string to "" |
||
repeat 5 times |
repeat 5 times |
||
set final_string to final_string & str |
set final_string to final_string & str |
||
end repeat</ |
end repeat</syntaxhighlight> |
||
Line 120: | Line 315: | ||
{{trans|JavaScript}} |
{{trans|JavaScript}} |
||
< |
<syntaxhighlight lang="applescript">replicate(5000, "ha") |
||
-- Repetition by 'Egyptian multiplication' - |
-- Repetition by 'Egyptian multiplication' - |
||
Line 139: | Line 334: | ||
end repeat |
end repeat |
||
return out & dbl |
return out & dbl |
||
end replicate</ |
end replicate</syntaxhighlight> |
||
=={{header|Applesoft BASIC}}== |
=={{header|Applesoft BASIC}}== |
||
< |
<syntaxhighlight lang="applesoftbasic">FOR I = 1 TO 5 : S$ = S$ + "HA" : NEXT |
||
? "X" SPC(20) "X"</ |
? "X" SPC(20) "X"</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>X X</pre> |
<pre>X X</pre> |
||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
<syntaxhighlight lang="rebol">print repeat "ha" 5</syntaxhighlight> |
|||
<lang arturo>str: "ha" * 5 |
|||
print str</lang> |
|||
{{out}} |
{{out}} |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
=={{header|ATS}}== |
|||
<lang ATS> |
|||
// |
|||
// How to compile: |
|||
// patscc -DATS_MEMALLOC_LIBC -o string_repeat string_repeat.dats |
|||
// |
|||
#include |
|||
"share/atspre_staload.hats" |
|||
fun |
|||
string_repeat |
|||
( |
|||
x: string, n: intGte(0) |
|||
) : Strptr1 = res where |
|||
{ |
|||
val xs = |
|||
list_make_elt<string>(n, x) |
|||
val res = stringlst_concat($UNSAFE.list_vt2t(xs)) |
|||
val ((*freed*)) = list_vt_free(xs) |
|||
} (* end of [string_repeat] *) |
|||
(* ****** ****** *) |
|||
implement |
|||
main0 () = let |
|||
// |
|||
val ha5 = string_repeat("ha", 5) |
|||
val ((*void*)) = println! ("ha5 = \"", ha5, "\"") |
|||
val ((*freed*)) = strptr_free (ha5) |
|||
// |
|||
in |
|||
// nothing |
|||
end // end of [main0] |
|||
</lang> |
|||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">MsgBox % Repeat("ha",5) |
||
Repeat(String,Times) |
Repeat(String,Times) |
||
Line 201: | Line 358: | ||
Output .= String |
Output .= String |
||
Return Output |
Return Output |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AutoIt}}== |
=={{header|AutoIt}}== |
||
< |
<syntaxhighlight lang="autoit">#include <String.au3> |
||
ConsoleWrite(_StringRepeat("ha", 5) & @CRLF)</ |
ConsoleWrite(_StringRepeat("ha", 5) & @CRLF)</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
< |
<syntaxhighlight lang="awk">function repeat( str, n, rep, i ) |
||
{ |
{ |
||
for( ; i<n; i++ ) |
for( ; i<n; i++ ) |
||
Line 218: | Line 375: | ||
BEGIN { |
BEGIN { |
||
print repeat( "ha", 5 ) |
print repeat( "ha", 5 ) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Babel}}== |
=={{header|Babel}}== |
||
< |
<syntaxhighlight lang="babel">main: { "ha" 5 print_repeat } |
||
print_repeat!: { <- { dup << } -> times }</ |
print_repeat!: { <- { dup << } -> times }</syntaxhighlight> |
||
Outputs: |
Outputs: |
||
<lang |
<syntaxhighlight lang="babel">hahahahaha</syntaxhighlight> |
||
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]] |
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]] |
||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
To repeat a string: |
To repeat a string: |
||
< |
<syntaxhighlight lang="qbasic">DOTIMES 5 |
||
s$ = s$ & "ha" |
s$ = s$ & "ha" |
||
DONE |
DONE |
||
PRINT s$</ |
PRINT s$</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 239: | Line 396: | ||
</pre> |
</pre> |
||
To repeat one single character: |
To repeat one single character: |
||
< |
<syntaxhighlight lang="qbasic">PRINT FILL$(5, ASC("x"))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
xxxxx |
xxxxx |
||
</pre> |
</pre> |
||
=={{header|BASIC}}== |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="basic256">function StringRepeat$ (s$, n) |
|||
cad$ = "" |
|||
for i = 1 to n |
|||
cad$ += s$ |
|||
next i |
|||
return cad$ |
|||
end function |
|||
print StringRepeat$("rosetta", 1) |
|||
print StringRepeat$("ha", 5) |
|||
print StringRepeat$("*", 5) |
|||
end</syntaxhighlight> |
|||
==={{header|Chipmunk Basic}}=== |
|||
{{works with|Chipmunk Basic|3.6.4}} |
|||
<syntaxhighlight lang="qbasic">100 cls |
|||
110 print stringrepeat$("rosetta",1) |
|||
120 print stringrepeat$("ha",5) |
|||
130 print stringrepeat$("*",5) |
|||
140 end |
|||
150 function stringrepeat$(s$,n) |
|||
160 cad$ = "" |
|||
170 for i = 1 to n |
|||
180 cad$ = cad$+s$ |
|||
190 next i |
|||
200 stringrepeat$ = cad$ |
|||
210 end function</syntaxhighlight> |
|||
==={{header|GW-BASIC}}=== |
|||
{{works with|Applesoft BASIC}} |
|||
{{works with|PC-BASIC|any}} |
|||
{{works with|BASICA}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|QBasic}} |
|||
{{works with|MSX BASIC}} |
|||
<syntaxhighlight lang="qbasic">100 CLS : rem 100 HOME for Applesoft BASIC |
|||
110 S$ = "rosetta" : N = 1 |
|||
120 GOSUB 210 |
|||
130 PRINT CAD$ |
|||
140 S$ = "ha" : N = 5 |
|||
150 GOSUB 210 |
|||
160 PRINT CAD$ |
|||
170 S$ = "*" : N = 5 |
|||
180 GOSUB 210 |
|||
190 PRINT CAD$ |
|||
200 END |
|||
210 REM FUNCTION STRINGREPEAT$(S$,N) |
|||
220 CAD$ = "" |
|||
230 FOR I = 1 TO N |
|||
240 CAD$ = CAD$+S$ |
|||
250 NEXT I |
|||
260 RETURN</syntaxhighlight> |
|||
==={{header|Minimal BASIC}}=== |
|||
{{works with|Quite BASIC}} |
|||
<syntaxhighlight lang="qbasic">100 REM Repeat a string |
|||
110 LET S$ = "rosetta" |
|||
120 LET N = 1 |
|||
130 GOSUB 210 |
|||
140 LET S$ = "ha" |
|||
150 LET N = 5 |
|||
160 GOSUB 210 |
|||
170 LET S$ = "*" |
|||
180 LET N = 5 |
|||
190 GOSUB 210 |
|||
200 STOP |
|||
210 REM FUNCTION StringRepeat$(S$,N) |
|||
220 FOR I = 1 TO N |
|||
230 PRINT S$; |
|||
240 NEXT I |
|||
250 PRINT |
|||
260 RETURN |
|||
270 END</syntaxhighlight> |
|||
==={{header|MSX Basic}}=== |
|||
{{works with|MSX BASIC|any}} |
|||
The [[#GW-BASIC|GW-BASIC]] solution works without any changes. |
|||
==={{header|QBasic}}=== |
|||
<syntaxhighlight lang="qbasic">FUNCTION StringRepeat$ (s$, n) |
|||
cad$ = "" |
|||
FOR i = 1 TO n |
|||
cad$ = cad$ + s$ |
|||
NEXT i |
|||
StringRepeat$ = cad$ |
|||
END FUNCTION |
|||
PRINT StringRepeat$("rosetta", 1) |
|||
PRINT StringRepeat$("ha", 5) |
|||
PRINT StringRepeat$("*", 5) |
|||
END</syntaxhighlight> |
|||
==={{header|Quite BASIC}}=== |
|||
{{works with|BASICA}} |
|||
{{works with|Chipmunk Basic}} |
|||
{{works with|GW-BASIC}} |
|||
{{works with|MSX BASIC}} |
|||
{{works with|PC-BASIC|any}} |
|||
{{works with|QBasic}} |
|||
<syntaxhighlight lang="qbasic">100 CLS |
|||
110 LET S$ = "rosetta" |
|||
115 LET N = 1 |
|||
120 GOSUB 210 |
|||
130 PRINT C$ |
|||
140 LET S$ = "ha" |
|||
145 LET N = 5 |
|||
150 GOSUB 210 |
|||
160 PRINT C$ |
|||
170 LET S$ = "*" |
|||
175 LET N = 5 |
|||
180 GOSUB 210 |
|||
190 PRINT C$ |
|||
200 END |
|||
210 REM FUNCTION STRINGREPEAT$(S$,N) |
|||
220 LET C$ = "" |
|||
230 FOR I = 1 TO N |
|||
240 LET C$ = C$ + S$ |
|||
250 NEXT I |
|||
260 RETURN</syntaxhighlight> |
|||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">FUNCTION StringRepeat$ (s$, n) |
|||
LET cad$ = "" |
|||
FOR i = 1 TO n |
|||
LET cad$ = cad$ & s$ |
|||
NEXT i |
|||
LET StringRepeat$ = cad$ |
|||
END FUNCTION |
|||
PRINT StringRepeat$("rosetta", 1) |
|||
PRINT StringRepeat$("ha", 5) |
|||
PRINT StringRepeat$("*", 5) |
|||
END</syntaxhighlight> |
|||
==={{header|XBasic}}=== |
|||
{{works with|Windows XBasic}} |
|||
<syntaxhighlight lang="qbasic">PROGRAM "Repeat a string" |
|||
VERSION "0.0000" |
|||
DECLARE FUNCTION Entry () |
|||
DECLARE FUNCTION StringRepeat$ (s$, n) |
|||
FUNCTION Entry () |
|||
PRINT StringRepeat$ ("rosetta", 1) |
|||
PRINT StringRepeat$ ("ha", 5) |
|||
PRINT StringRepeat$ ("*", 5) |
|||
END FUNCTION |
|||
FUNCTION StringRepeat$ (s$, n) |
|||
cad$ = "" |
|||
FOR i = 1 TO n |
|||
cad$ = cad$ + s$ |
|||
NEXT i |
|||
RETURN cad$ |
|||
END FUNCTION |
|||
END PROGRAM</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic">sub StringRepeat$ (s$, n) |
|||
cad$ = "" |
|||
for i = 1 to n |
|||
cad$ = cad$ + s$ |
|||
next i |
|||
return cad$ |
|||
end sub |
|||
print StringRepeat$("rosetta", 1) |
|||
print StringRepeat$("ha", 5) |
|||
print StringRepeat$("*", 5) |
|||
end</syntaxhighlight> |
|||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
Commandline implementation |
Commandline implementation |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
if "%2" equ "" goto fail |
if "%2" equ "" goto fail |
||
setlocal enabledelayedexpansion |
setlocal enabledelayedexpansion |
||
Line 254: | Line 587: | ||
for /l %%i in (1,1,%num%) do set res=!res!%char% |
for /l %%i in (1,1,%num%) do set res=!res!%char% |
||
echo %res% |
echo %res% |
||
:fail</ |
:fail</syntaxhighlight> |
||
'Function' version |
'Function' version |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
set /p a=Enter string to repeat : |
set /p a=Enter string to repeat : |
||
set /p b=Enter how many times to repeat : |
set /p b=Enter how many times to repeat : |
||
Line 266: | Line 599: | ||
set "c=%c%+=1" |
set "c=%c%+=1" |
||
if /i _"%c%"==_"%d%" (exit /b) |
if /i _"%c%"==_"%d%" (exit /b) |
||
goto :a</ |
goto :a</syntaxhighlight> |
||
'Function' version 2 |
'Function' version 2 |
||
< |
<syntaxhighlight lang="dos">@echo off |
||
@FOR /L %%i in (0,1,9) DO @CALL :REPEAT %%i |
@FOR /L %%i in (0,1,9) DO @CALL :REPEAT %%i |
||
@echo That's it! |
@echo That's it! |
||
Line 281: | Line 614: | ||
@GOTO:EOF |
@GOTO:EOF |
||
:END</ |
:END</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
< |
<syntaxhighlight lang="bbcbasic"> PRINT STRING$(5, "ha")</syntaxhighlight> |
||
=={{header|beeswax}}== |
=={{header|beeswax}}== |
||
< |
<syntaxhighlight lang="beeswax"> p < |
||
p0~1<}~< d@< |
p0~1<}~< d@< |
||
_VT@1~>yg~9PKd@M'd;</ |
_VT@1~>yg~9PKd@M'd;</syntaxhighlight> |
||
Line 301: | Line 634: | ||
<code>s</code> tells the user that the program expects a string as input. |
<code>s</code> tells the user that the program expects a string as input. |
||
<code>i</code> tells the user that the program expects an integer as input. |
<code>i</code> tells the user that the program expects an integer as input. |
||
=={{header|Beef}}== |
|||
<syntaxhighlight lang="csharp"> |
|||
String s = new String('X', 5); |
|||
s.Replace("X", "ha"); |
|||
</syntaxhighlight> |
|||
And for single character repeats |
|||
<syntaxhighlight lang="csharp"> |
|||
String s1 = scope .(); |
|||
s1.PadLeft(5, '*'); |
|||
</syntaxhighlight> |
|||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
< |
<syntaxhighlight lang="befunge">v> ">:#,_v |
||
>29*+00p>~:"0"- #v_v $ |
>29*+00p>~:"0"- #v_v $ |
||
v ^p0p00:-1g00< $ > |
v ^p0p00:-1g00< $ > |
||
v p00&p0-1g00+4*65< >00g1-:00p#^_@</ |
v p00&p0-1g00+4*65< >00g1-:00p#^_@</syntaxhighlight> |
||
Input sample: |
Input sample: |
||
<pre>ha05</pre> |
<pre>ha05</pre> |
||
Line 313: | Line 661: | ||
Output sample: |
Output sample: |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
=={{header|BQN}}== |
|||
<code>⥊</code>(reshape) can all by itself be used to repeat a string to a particular length. This function is just a wrapper around it to repeat n times. |
|||
<syntaxhighlight lang="bqn">Repeat ← ×⟜≠ ⥊ ⊢ |
|||
•Show 5 Repeat "Hello"</syntaxhighlight><syntaxhighlight lang="text">"HelloHelloHelloHelloHello"</syntaxhighlight> |
|||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
The code almost explains itself. The repetions are accumulated in a list <code>rep</code>. The <code>str</code> concatenates all elements into a single string, ignoring the white spaces separating the elements. |
The code almost explains itself. The repetions are accumulated in a list <code>rep</code>. The <code>str</code> concatenates all elements into a single string, ignoring the white spaces separating the elements. |
||
< |
<syntaxhighlight lang="bracmat">(repeat= |
||
string N rep |
string N rep |
||
. !arg:(?string.?N) |
. !arg:(?string.?N) |
||
Line 324: | Line 680: | ||
' (!N+-1:>0:?N&!string !rep:?rep) |
' (!N+-1:>0:?N&!string !rep:?rep) |
||
& str$!rep |
& str$!rep |
||
);</ |
);</syntaxhighlight> |
||
<pre> repeat$(ha.5) |
<pre> repeat$(ha.5) |
||
Line 331: | Line 687: | ||
=={{header|Brainf***}}== |
=={{header|Brainf***}}== |
||
Prints "ha" 10 times. Note that this method only works for a number of repetitions that fit into the cell size. |
Prints "ha" 10 times. Note that this method only works for a number of repetitions that fit into the cell size. |
||
< |
<syntaxhighlight lang="bf">+++++ +++++ init first as 10 counter |
||
[-> +++++ +++++<] we add 10 to second each loopround |
[-> +++++ +++++<] we add 10 to second each loopround |
||
Line 339: | Line 695: | ||
and a newline because I'm kind and it looks good |
and a newline because I'm kind and it looks good |
||
+++++ +++++ +++ . --- .</ |
+++++ +++++ +++ . --- .</syntaxhighlight> |
||
=={{header|Brat}}== |
=={{header|Brat}}== |
||
< |
<syntaxhighlight lang="brat">p "ha" * 5 #Prints "hahahahaha"</syntaxhighlight> |
||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
blsq ) 'h5?* |
blsq ) 'h5?* |
||
"hhhhh" |
"hhhhh" |
||
blsq ) "ha"5.*\[ |
blsq ) "ha"5.*\[ |
||
"hahahahaha" |
"hahahahaha" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 374: | Line 730: | ||
free(result); |
free(result); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
A variation. |
A variation. |
||
< |
<syntaxhighlight lang="c">... |
||
char *string_repeat(const char *str, int n) |
char *string_repeat(const char *str, int n) |
||
{ |
{ |
||
Line 388: | Line 744: | ||
while (pa>=dest) *pa-- = *pb--; |
while (pa>=dest) *pa-- = *pb--; |
||
return dest; |
return dest; |
||
}</ |
}</syntaxhighlight> |
||
To repeat a single character |
To repeat a single character |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
#include <string.h> |
#include <string.h> |
||
Line 407: | Line 763: | ||
free(result); |
free(result); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
If you use [[GLib]], simply use <code>g_strnfill ( gsize length, gchar fill_char )</code> function. |
If you use [[GLib]], simply use <code>g_strnfill ( gsize length, gchar fill_char )</code> function. |
||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="csharp">string s = "".PadLeft(5, 'X').Replace("X", "ha");</syntaxhighlight> |
||
or (with .NET 2+) |
or (with .NET 2+) |
||
< |
<syntaxhighlight lang="csharp">string s = new String('X', 5).Replace("X", "ha");</syntaxhighlight> |
||
or (with .NET 2+) |
or (with .NET 2+) |
||
< |
<syntaxhighlight lang="csharp">string s = String.Join("ha", new string[5 + 1]);</syntaxhighlight> |
||
or (with .NET 4+) |
or (with .NET 4+) |
||
< |
<syntaxhighlight lang="csharp">string s = String.Concat(Enumerable.Repeat("ha", 5));</syntaxhighlight> |
||
To repeat a single character: |
To repeat a single character: |
||
< |
<syntaxhighlight lang="csharp">string s = "".PadLeft(5, '*');</syntaxhighlight> |
||
or (with .NET 2+) |
or (with .NET 2+) |
||
< |
<syntaxhighlight lang="csharp">string s = new String('*', 5);</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <string> |
||
#include <iostream> |
#include <iostream> |
||
Line 440: | Line 796: | ||
std::cout << repeat( "Ha" , 5 ) << std::endl ; |
std::cout << repeat( "Ha" , 5 ) << std::endl ; |
||
return 0 ; |
return 0 ; |
||
}</ |
}</syntaxhighlight> |
||
To repeat a single character: |
To repeat a single character: |
||
< |
<syntaxhighlight lang="cpp">#include <string> |
||
#include <iostream> |
#include <iostream> |
||
Line 449: | Line 805: | ||
std::cout << std::string( 5, '*' ) << std::endl ; |
std::cout << std::string( 5, '*' ) << std::endl ; |
||
return 0 ; |
return 0 ; |
||
}</ |
}</syntaxhighlight> |
||
=== recursive version === |
|||
<syntaxhighlight lang="cpp">#include <string> |
|||
#include <iostream> |
|||
std::string repeat( const std::string &word, uint times ) { |
|||
return |
|||
times == 0 ? "" : |
|||
times == 1 ? word : |
|||
times == 2 ? word + word : |
|||
repeat(repeat(word, times / 2), 2) + |
|||
repeat(word, times % 2); |
|||
} |
|||
int main( ) { |
|||
std::cout << repeat( "Ha" , 5 ) << std::endl ; |
|||
return 0 ; |
|||
}</syntaxhighlight> |
|||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void repeatAString() { |
||
print("ha".repeat(5)); |
print("ha".repeat(5)); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clipper}}== |
=={{header|Clipper}}== |
||
Also works with Harbour Project compiler Harbour 3.0.0 (Rev. 16951) |
Also works with Harbour Project compiler Harbour 3.0.0 (Rev. 16951) |
||
< |
<syntaxhighlight lang="visualfoxpro"> Replicate( "Ha", 5 )</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="lisp">(apply str (repeat 5 "ha"))</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Virtually a one-liner. |
Virtually a one-liner. |
||
< |
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION. |
||
PROGRAM-ID. REPEAT-PROGRAM. |
PROGRAM-ID. REPEAT-PROGRAM. |
||
DATA DIVISION. |
DATA DIVISION. |
||
Line 473: | Line 847: | ||
MOVE ALL 'ha' TO HAHA. |
MOVE ALL 'ha' TO HAHA. |
||
DISPLAY HAHA. |
DISPLAY HAHA. |
||
STOP RUN.</ |
STOP RUN.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
=={{header|ColdFusion}}== |
=={{header|ColdFusion}}== |
||
< |
<syntaxhighlight lang="cfm"> |
||
<cfset word = 'ha'> |
<cfset word = 'ha'> |
||
<Cfset n = 5> |
<Cfset n = 5> |
||
Line 484: | Line 858: | ||
<Cfloop from="1" to="#n#" index="i">#word#</Cfloop> |
<Cfloop from="1" to="#n#" index="i">#word#</Cfloop> |
||
</Cfoutput> |
</Cfoutput> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun repeat-string (n string) |
||
(with-output-to-string (stream) |
(with-output-to-string (stream) |
||
(loop repeat n do (write-string string stream))))</ |
(loop repeat n do (write-string string stream))))</syntaxhighlight> |
||
A version which allocates the result string in one step: |
A version which allocates the result string in one step: |
||
< |
<syntaxhighlight lang="lisp">(defun repeat-string (n string |
||
&aux |
&aux |
||
(len (length string)) |
(len (length string)) |
||
Line 501: | Line 875: | ||
for i from 0 by len |
for i from 0 by len |
||
do (setf (subseq result i (+ i len)) string)) |
do (setf (subseq result i (+ i len)) string)) |
||
result)</ |
result)</syntaxhighlight> |
||
For those who love one-liners, even at the expense of readability: |
For those who love one-liners, even at the expense of readability: |
||
< |
<syntaxhighlight lang="lisp">(defun repeat-string (n string) |
||
(format nil "~V@{~a~:*~}" n string))</ |
(format nil "~V@{~a~:*~}" n string))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lisp">(princ (repeat-string 5 "hi"))</syntaxhighlight> |
||
A single character may be repeated using just the builtin <code>make-string</code>: |
A single character may be repeated using just the builtin <code>make-string</code>: |
||
< |
<syntaxhighlight lang="lisp">(make-string 5 :initial-element #\X)</syntaxhighlight> |
||
produces “XXXXX”. |
produces “XXXXX”. |
||
=={{header|Crystal}}== |
=={{header|Crystal}}== |
||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
puts "ha" * 5 |
puts "ha" * 5 |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre>hahahahaha</pre> |
|||
<lang Bash> |
|||
hahahahaha |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
Repeating a string: |
Repeating a string: |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.array; |
||
void main() { |
void main() { |
||
writeln("ha".replicate(5)); |
writeln("ha".replicate(5)); |
||
}</ |
}</syntaxhighlight> |
||
Repeating a character with vector operations: |
Repeating a character with vector operations: |
||
< |
<syntaxhighlight lang="d">import std.stdio; |
||
void main() { |
void main() { |
||
Line 540: | Line 912: | ||
chars[] = '*'; // set all characters in the string to '*' |
chars[] = '*'; // set all characters in the string to '*' |
||
writeln(chars); |
writeln(chars); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|DCL}}== |
=={{header|DCL}}== |
||
Not exactly what the task asks for but at least it is something; |
Not exactly what the task asks for but at least it is something; |
||
< |
<syntaxhighlight lang="dcl">$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" ) |
||
$ write sys$output f$fao( "!12*d" )</ |
$ write sys$output f$fao( "!12*d" )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>$ @repeat_a_string_and_then_character |
<pre>$ @repeat_a_string_and_then_character |
||
Line 553: | Line 925: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Repeat a string |
Repeat a string |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
function RepeatString(const s: string; count: cardinal): string; |
function RepeatString(const s: string; count: cardinal): string; |
||
var |
var |
||
Line 563: | Line 935: | ||
Writeln(RepeatString('ha',5)); |
Writeln(RepeatString('ha',5)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Repeat a character |
Repeat a character |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
Writeln( StringOfChar('a',5) ); |
Writeln( StringOfChar('a',5) ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using recursion |
Using recursion |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
function RepeatStr(const s: string; i: Cardinal): string; |
function RepeatStr(const s: string; i: Cardinal): string; |
||
begin |
begin |
||
Line 581: | Line 953: | ||
result := s + RepeatStr(s, i-1) |
result := s + RepeatStr(s, i-1) |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Built in RTL function: |
Built in RTL function: |
||
<lang |
<syntaxhighlight lang="delphi">StrUtils.DupeString</syntaxhighlight> |
||
=={{header|DWScript}}== |
=={{header|DWScript}}== |
||
Repeat a string |
Repeat a string |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
PrintLn( StringOfString('abc',5) ); |
PrintLn( StringOfString('abc',5) ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Repeat a character |
Repeat a character |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
PrintLn( StringOfChar('a',5) ); |
PrintLn( StringOfChar('a',5) ); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
<lang |
<syntaxhighlight lang="dyalect">String.Repeat("ha", 5)</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">!. concat( rep 5 "ha" )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"hahahahaha"</pre> |
<pre>"hahahahaha"</pre> |
||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">"ha" * 5</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang=easylang> |
|||
func$ rep s$ n . |
|||
for i to n |
|||
r$ &= s$ |
|||
. |
|||
return r$ |
|||
. |
|||
print rep "ha" 5 |
|||
</syntaxhighlight> |
|||
=={{header|ECL}}== |
=={{header|ECL}}== |
||
After version 4.2.2 |
After version 4.2.2 |
||
<lang>IMPORT STD; //Imports the Standard Library |
<syntaxhighlight lang="text">IMPORT STD; //Imports the Standard Library |
||
STRING MyBaseString := 'abc'; |
STRING MyBaseString := 'abc'; |
||
RepeatedString := STD.Str.Repeat(MyBaseString,3); |
RepeatedString := STD.Str.Repeat(MyBaseString,3); |
||
RepeatedString; //returns 'abcabcabc'</ |
RepeatedString; //returns 'abcabcabc'</syntaxhighlight> |
||
Before version 4.2.2 |
Before version 4.2.2 |
||
<lang>RepeatString(STRING InStr, INTEGER Cnt) := FUNCTION |
<syntaxhighlight lang="text">RepeatString(STRING InStr, INTEGER Cnt) := FUNCTION |
||
rec := {STRING Str}; |
rec := {STRING Str}; |
||
ds := DATASET(Cnt,TRANSFORM(rec,SELF.Str := InStr)); |
ds := DATASET(Cnt,TRANSFORM(rec,SELF.Str := InStr)); |
||
Line 628: | Line 1,011: | ||
RepeatString('ha',3); |
RepeatString('ha',3); |
||
RepeatString('Who',2);</ |
RepeatString('Who',2);</syntaxhighlight> |
||
=={{header|Ecstasy}}== |
|||
<syntaxhighlight lang="java"> |
|||
String funny = "ha" * 5; |
|||
String stars = '*' * 80; |
|||
</syntaxhighlight> |
|||
=={{header|Egison}}== |
=={{header|Egison}}== |
||
< |
<syntaxhighlight lang="egison"> |
||
(S.concat (take 5 (repeat1 "ha"))) |
(S.concat (take 5 (repeat1 "ha"))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel"> |
||
repeat_string(a_string: STRING; times: INTEGER): STRING |
repeat_string(a_string: STRING; times: INTEGER): STRING |
||
require |
require |
||
Line 643: | Line 1,032: | ||
Result := a_string.multiply(times) |
Result := a_string.multiply(times) |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA |
ELENA 6.x : |
||
< |
<syntaxhighlight lang="elena">import system'routines; |
||
import extensions; |
import extensions; |
||
import extensions'text; |
import extensions'text; |
||
Line 653: | Line 1,042: | ||
public program() |
public program() |
||
{ |
{ |
||
var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter()) |
var s := new Range(0, 5).selectBy::(x => "ha").summarize(new StringWriter()) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir"> |
||
String.duplicate("ha", 5) |
String.duplicate("ha", 5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
Going via a list to repeat the desired string |
Going via a list to repeat the desired string: |
||
< |
<syntaxhighlight lang="lisp">(apply 'concat (make-list 5 "ha"))</syntaxhighlight> |
||
A single character can be repeated with <code>make-string</code> |
A single character can be repeated with <code>make-string</code>: |
||
<lang |
<syntaxhighlight lang="lisp">(make-string 5 ?x)</syntaxhighlight> |
||
The <code>cl-loop</code> macro can repeat and concatenate: |
|||
{{libheader|cl-lib}} |
|||
<lang lisp>(require 'cl) |
|||
<syntaxhighlight lang="lisp">(require 'cl-lib) |
|||
(loop repeat 5 concat "ha")</lang> |
|||
(cl-loop repeat 5 concat "ha")</syntaxhighlight> |
|||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
< |
<syntaxhighlight lang="erlang">repeat(X,N) -> |
||
lists:flatten(lists:duplicate(N,X)).</ |
lists:flatten(lists:duplicate(N,X)).</syntaxhighlight> |
||
This will duplicate a string or character N times to produce a new string. |
This will duplicate a string or character N times to produce a new string. |
||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROCEDURE REPEAT_STRING(S$,N%->REP$) |
PROCEDURE REPEAT_STRING(S$,N%->REP$) |
||
LOCAL I% |
LOCAL I% |
||
Line 689: | Line 1,079: | ||
END FOR |
END FOR |
||
END PROCEDURE |
END PROCEDURE |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note: If N% is less than 1, the result is the empty string "".If S$ is a one-character string |
Note: If N% is less than 1, the result is the empty string "".If S$ is a one-character string |
||
you can use the predefined function <code>STRING$</code> as <code>REP$=STRING$(S$,N%)</code>. |
you can use the predefined function <code>STRING$</code> as <code>REP$=STRING$(S$,N%)</code>. |
||
[[File:=={{header|Euphoria}}== |
|||
<lang 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 |
|||
=={{header|Euphoria}}== |
|||
puts(1,repeat_string("ha",5) & '\n') -- hahahahaha |
|||
A simple loop will do: |
|||
<syntaxhighlight lang="euphoria"> |
|||
sequence s = "" |
|||
for i = 1 to 5 do s &= "ha" end for |
|||
puts(1,s) |
|||
puts(1,repeat_string('*',5) & '\n') -- *****</lang> |
|||
Sample Output: |
|||
<pre> |
|||
hahahahaha |
hahahahaha |
||
</syntaxhighlight> |
|||
*****</pre> |
|||
For repeating a single character: |
|||
<lang Euphoria>-- Here is an alternative method for "Repeat a string" |
|||
<syntaxhighlight lang="euphoria"> |
|||
include std/sequence.e |
|||
sequence s = repeat('*',5) |
|||
printf(1,"Here is the repeated string: %s\n", {repeat_pattern("ha",5)}) |
|||
printf(1,"Here is another: %s\n", {repeat_pattern("*",5)}) |
|||
***** |
|||
</lang> |
|||
</syntaxhighlight> |
|||
Sample Output: |
|||
<pre> |
|||
For repeating a string or sequence of numbers: |
|||
Here is the repeated string: hahahahaha |
|||
<syntaxhighlight lang="euphoria"> |
|||
Here is another: *****</pre> |
|||
include std/console.e -- for display |
|||
include std/sequence.e -- for repeat_pattern |
|||
sequence s = repeat_pattern("ha",5) |
|||
sequence n = repeat_pattern({1,2,3},5) |
|||
display(s) |
|||
display(n) |
|||
hahahahaha |
|||
{1,2,3,1,2,3,1,2,3,1,2,3,1,2,3} |
|||
</syntaxhighlight> |
|||
But wait, here's another way: |
|||
<syntaxhighlight lang="euphoria"> |
|||
include std/console.e -- for display |
|||
include std/sequence.e -- for flatten |
|||
sequence s = flatten(repeat("ha",5)) |
|||
display(s) |
|||
</syntaxhighlight> |
|||
note: repeat creates a sequence of ha's as shown below; flatten concatenates them. |
|||
<syntaxhighlight lang="euphoria"> |
|||
{ |
|||
"ha", |
|||
"ha", |
|||
"ha", |
|||
"ha", |
|||
"ha" |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Explore}}== |
=={{header|Explore}}== |
||
The [[Scratch]] [[Repeat a string#Scratch|solution]], which requires making variables named "String", "Count", and "Repeated" first, works, unmodified:<br>https://i.ibb.co/yX3ybt7/Repeat-a-string-in-Explore-using-the-Scratch-solution.png |
|||
This example uses a special block located in the Strings category, and also outputs the results of the repeating of the string to a "say" block:<br>https://i.ibb.co/71x9rwn/Repeat-a-string-in-Explore-using-a-special-block.png |
This example uses a special block located in the Strings category, and also outputs the results of the repeating of the string to a "say" block:<br>https://i.ibb.co/71x9rwn/Repeat-a-string-in-Explore-using-a-special-block.png |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">> String.replicate 5 "ha";; |
||
val it : string = "hahahahaha"</ |
val it : string = "hahahahaha"</syntaxhighlight> |
||
Or |
Or |
||
< |
<syntaxhighlight lang="fsharp">> String.Concat( Array.create 5 "ha" );; |
||
val it : string = "hahahahaha"</ |
val it : string = "hahahahaha"</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">: repeat-string ( str n -- str' ) swap <repetition> concat ; |
||
"ha" 5 repeat-string print</ |
"ha" 5 repeat-string print</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: place-n { src len dest n -- } |
||
0 dest c! |
0 dest c! |
||
n 0 ?do src len dest +place loop ; |
n 0 ?do src len dest +place loop ; |
||
s" ha" pad 5 place-n |
s" ha" pad 5 place-n |
||
pad count type \ hahahahaha</ |
pad count type \ hahahahaha</syntaxhighlight> |
||
The same code without the use of locals: |
The same code without the use of locals: |
||
< |
<syntaxhighlight lang="forth"> |
||
: place-n ( src len dest n -- ) |
: place-n ( src len dest n -- ) |
||
swap >r 0 r@ c! |
swap >r 0 r@ c! |
||
Line 757: | Line 1,165: | ||
s" ha" pad 5 place-n |
s" ha" pad 5 place-n |
||
pad count type \ hahahahaha</ |
pad count type \ hahahahaha</syntaxhighlight> |
||
Filling a string with a single character is supported by ANS-Forth: |
Filling a string with a single character is supported by ANS-Forth: |
||
< |
<syntaxhighlight lang="forth">pad 10 char * fill \ repeat a single character |
||
pad 10 type \ **********</ |
pad 10 type \ **********</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with |Fortran|90 and later}} |
{{works with |Fortran|90 and later}} |
||
< |
<syntaxhighlight lang="fortran">program test_repeat |
||
write (*, '(a)') repeat ('ha', 5) |
write (*, '(a)') repeat ('ha', 5) |
||
end program test_repeat</ |
end program test_repeat</syntaxhighlight> |
||
Output: |
Output: |
||
hahahahaha |
hahahahaha |
||
=={{header|Free Pascal}}== |
=={{header|Free Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">strUtils.dupeString('ha', 5)</syntaxhighlight> |
||
Repetition of a single character: |
Repetition of a single character: |
||
<lang |
<syntaxhighlight lang="pascal">stringOfChar('*', 5)</syntaxhighlight> |
||
If the repeated character happens to be the space character: |
If the repeated character happens to be the space character: |
||
<lang |
<syntaxhighlight lang="pascal">space(5)</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
' A character is essentially a string of length 1 in FB though there is a built-in function, String, |
' A character is essentially a string of length 1 in FB though there is a built-in function, String, |
||
Line 808: | Line 1,216: | ||
Print |
Print |
||
Print "Press any key to quit program" |
Print "Press any key to quit program" |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 818: | Line 1,226: | ||
=={{header|Frink}}== |
=={{header|Frink}}== |
||
< |
<syntaxhighlight lang="frink"> |
||
println[repeat["ha", 5]] |
println[repeat["ha", 5]] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
include "NSLog.incl" |
|||
CFStringRef repeatStr |
|||
repeatStr = @"Hello, World!\n" |
|||
NSLog( @"%@", fn StringByPaddingToLength( @"", 50 * len(repeatStr), repeatStr, 0 ) ) |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
[50 line repetitions of "Hello, World!"] |
|||
</pre> |
|||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=bdd2a7a0f4f09ff67e9d78b5d9667bdb Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=bdd2a7a0f4f09ff67e9d78b5d9667bdb Click this link to run this code]''' |
||
<lang>Public Sub Main() |
<syntaxhighlight lang="text">Public Sub Main() |
||
Print String$(5, "ha") |
Print String$(5, "ha") |
||
End</ |
End</syntaxhighlight> |
||
Output = hahahahaha |
Output = hahahahaha |
||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap">Concatenation(ListWithIdenticalEntries(10, "BOB ")); |
||
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "</ |
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "</syntaxhighlight> |
||
=={{header|Glee}}== |
=={{header|Glee}}== |
||
<lang |
<syntaxhighlight lang="glee">'*' %% 5</syntaxhighlight> |
||
< |
<syntaxhighlight lang="glee">'ha' => Str; |
||
Str# => Len; |
Str# => Len; |
||
1..Len %% (Len * 5) => Idx; |
1..Len %% (Len * 5) => Idx; |
||
Str [Idx] $;</ |
Str [Idx] $;</syntaxhighlight> |
||
< |
<syntaxhighlight lang="glee">'ha'=>S[1..(S#)%%(S# *5)]</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">fmt.Println(strings.Repeat("ha", 5)) // ==> "hahahahaha"</syntaxhighlight> |
||
There is no special way to repeat a single character, other than to convert the character to a string. The following works: |
There is no special way to repeat a single character, other than to convert the character to a string. The following works: |
||
< |
<syntaxhighlight lang="go">fmt.Println(strings.Repeat(string('h'), 5)) // prints hhhhh</syntaxhighlight> |
||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
<lang |
<syntaxhighlight lang="groovy"> println 'ha' * 5</syntaxhighlight> |
||
=={{header|Harbour}}== |
=={{header|Harbour}}== |
||
< |
<syntaxhighlight lang="visualfoxpro">? Replicate( "Ha", 5 )</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
For a string of finite length: |
For a string of finite length: |
||
< |
<syntaxhighlight lang="haskell">concat $ replicate 5 "ha"</syntaxhighlight> |
||
Or with list-monad (a bit obscure): |
Or with list-monad (a bit obscure): |
||
< |
<syntaxhighlight lang="haskell">[1..5] >> "ha"</syntaxhighlight> |
||
Or with Control.Applicative: |
Or with Control.Applicative: |
||
< |
<syntaxhighlight lang="haskell">[1..5] *> "ha"</syntaxhighlight> |
||
For an infinitely long string: |
For an infinitely long string: |
||
< |
<syntaxhighlight lang="haskell">cycle "ha"</syntaxhighlight> |
||
To repeat a single character: |
To repeat a single character: |
||
<lang |
<syntaxhighlight lang="haskell">replicate 5 '*'</syntaxhighlight> |
||
Or, unpacking the mechanism of '''replicate''' a little, and using a '''mappend'''-based rep in lieu of the '''cons'''-based '''repeat''', so that we can skip a subsequent '''concat''': |
Or, unpacking the mechanism of '''replicate''' a little, and using a '''mappend'''-based rep in lieu of the '''cons'''-based '''repeat''', so that we can skip a subsequent '''concat''': |
||
< |
<syntaxhighlight lang="haskell">repString :: String -> Int -> String |
||
repString s n = |
repString s n = |
||
let rep x = xs |
let rep x = xs |
||
Line 882: | Line 1,308: | ||
main :: IO () |
main :: IO () |
||
main = print $ repString "ha" 5</ |
main = print $ repString "ha" 5</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>"hahahahaha"</pre> |
<pre>"hahahahaha"</pre> |
||
Line 888: | Line 1,314: | ||
As the number of repetitions grows, however, it may become more efficient to repeat by progressive duplication (mappend to self), mappending to an accumulator only where required for binary composition of the target length. (i.e. Rhind Papyrus 'Egyptian' or 'Ethiopian' multiplication): |
As the number of repetitions grows, however, it may become more efficient to repeat by progressive duplication (mappend to self), mappending to an accumulator only where required for binary composition of the target length. (i.e. Rhind Papyrus 'Egyptian' or 'Ethiopian' multiplication): |
||
< |
<syntaxhighlight lang="haskell">import Data.Tuple (swap) |
||
import Data.List (unfoldr) |
import Data.List (unfoldr) |
||
import Control.Monad (join) |
import Control.Monad (join) |
||
Line 912: | Line 1,338: | ||
-- TEST ----------------------------------------------------------------------- |
-- TEST ----------------------------------------------------------------------- |
||
main :: IO () |
main :: IO () |
||
main = print $ repString 500 "ha"</ |
main = print $ repString 500 "ha"</syntaxhighlight> |
||
=={{header|HicEst}}== |
=={{header|HicEst}}== |
||
< |
<syntaxhighlight lang="hicest">CHARACTER out*20 |
||
EDIT(Text=out, Insert="ha", DO=5)</ |
EDIT(Text=out, Insert="ha", DO=5)</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
The procedure <tt>repl</tt> is a supplied function in Icon and Unicon. |
The procedure <tt>repl</tt> is a supplied function in Icon and Unicon. |
||
< |
<syntaxhighlight lang="icon">procedure main(args) |
||
write(repl(integer(!args) | 5)) |
write(repl(integer(!args) | 5)) |
||
end</ |
end</syntaxhighlight> |
||
If it weren't, one way to write it is: |
If it weren't, one way to write it is: |
||
< |
<syntaxhighlight lang="icon">procedure repl(s, n) |
||
every (ns := "") ||:= |s\(0 <= n) |
every (ns := "") ||:= |s\(0 <= n) |
||
return ns |
return ns |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Idris}}== |
=={{header|Idris}}== |
||
< |
<syntaxhighlight lang="idris">strRepeat : Nat -> String -> String |
||
strRepeat Z s = "" |
strRepeat Z s = "" |
||
strRepeat (S n) s = s ++ strRepeat n s |
strRepeat (S n) s = s ++ strRepeat n s |
||
Line 937: | Line 1,363: | ||
chrRepeat : Nat -> Char -> String |
chrRepeat : Nat -> Char -> String |
||
chrRepeat Z c = "" |
chrRepeat Z c = "" |
||
chrRepeat (S n) c = strCons c $ chrRepeat n c</ |
chrRepeat (S n) c = strCons c $ chrRepeat n c</syntaxhighlight> |
||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
< |
<syntaxhighlight lang="inform7">Home is a room. |
||
To decide which indexed text is (T - indexed text) repeated (N - number) times: |
To decide which indexed text is (T - indexed text) repeated (N - number) times: |
||
Line 950: | Line 1,376: | ||
When play begins: |
When play begins: |
||
say "ha" repeated 5 times; |
say "ha" repeated 5 times; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
=={{Header|Insitux}}== |
|||
<syntaxhighlight lang="insitux"> |
|||
(str* "ha" 5) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hahahahaha |
|||
</pre> |
|||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
< |
<syntaxhighlight lang="is-basic"> 10 PRINT STRING$("ha",5) |
||
100 DEF STRING$(S$,N) |
100 DEF STRING$(S$,N) |
||
105 LET ST$="" |
105 LET ST$="" |
||
Line 960: | Line 1,398: | ||
130 NEXT |
130 NEXT |
||
140 LET STRING$=ST$ |
140 LET STRING$=ST$ |
||
150 END DEF</ |
150 END DEF</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
< |
<syntaxhighlight lang="j"> 5 # '*' NB. repeat each item 5 times |
||
***** |
***** |
||
5 # 'ha' NB. repeat each item 5 times |
5 # 'ha' NB. repeat each item 5 times |
||
Line 969: | Line 1,407: | ||
5 ((* #) $ ]) 'ha' NB. repeat array 5 times |
5 ((* #) $ ]) 'ha' NB. repeat array 5 times |
||
hahahahaha |
hahahahaha |
||
5 ;@# < 'ha' NB. boxing |
5 ;@# < 'ha' NB. using boxing to treat the array as a whole |
||
hahahahaha</ |
hahahahaha</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
There are a few ways to achieve this in Java.<br /> |
|||
Starting with Java 11 you can use the ''String.repeat'' method. |
|||
<syntaxhighlight lang="java"> |
|||
"ha".repeat(5); |
|||
</syntaxhighlight> |
|||
Which, if you view its implementation, is just using the ''Arrays.fill'' method. |
|||
<syntaxhighlight lang="java"> |
|||
String[] strings = new String[5]; |
|||
Arrays.fill(strings, "ha"); |
|||
StringBuilder repeated = new StringBuilder(); |
|||
for (String string : strings) |
|||
repeated.append(string); |
|||
</syntaxhighlight> |
|||
And if you look at the 'Arrays.fill' implementation, it's just a for-loop, which is likely the most idiomatic approach. |
|||
<syntaxhighlight lang="java"> |
|||
String string = "ha"; |
|||
StringBuilder repeated = new StringBuilder(); |
|||
int count = 5; |
|||
while (count-- > 0) |
|||
repeated.append(string); |
|||
</syntaxhighlight> |
|||
<br /> |
|||
Or |
|||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
||
Before Java 11 there was no method or operator to do this in Java, so you had to do it yourself. |
|||
< |
<syntaxhighlight lang="java5">public static String repeat(String str, int times) { |
||
StringBuilder sb = new StringBuilder(str.length() * times); |
StringBuilder sb = new StringBuilder(str.length() * times); |
||
for (int i = 0; i < times; i++) |
for (int i = 0; i < times; i++) |
||
Line 986: | Line 1,447: | ||
public static void main(String[] args) { |
public static void main(String[] args) { |
||
System.out.println(repeat("ha", 5)); |
System.out.println(repeat("ha", 5)); |
||
}</ |
}</syntaxhighlight> |
||
Or even shorter: |
Or even shorter: |
||
< |
<syntaxhighlight lang="java5">public static String repeat(String str, int times) { |
||
return new String(new char[times]).replace("\0", str); |
return new String(new char[times]).replace("\0", str); |
||
}</ |
}</syntaxhighlight> |
||
In Apache Commons Lang, there is a [http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html#repeat%28java.lang.String,%20int%29 StringUtils.repeat()] method. |
In Apache Commons Lang, there is a [http://commons.apache.org/lang/api-2.6/org/apache/commons/lang/StringUtils.html#repeat%28java.lang.String,%20int%29 StringUtils.repeat()] method. |
||
Line 999: | Line 1,460: | ||
====Extending the String prototype==== |
====Extending the String prototype==== |
||
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. |
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. |
||
< |
<syntaxhighlight lang="javascript">String.prototype.repeat = function(n) { |
||
return new Array(1 + (n || 0)).join(this); |
return new Array(1 + (n || 0)).join(this); |
||
} |
} |
||
console.log("ha".repeat(5)); // hahahahaha</ |
console.log("ha".repeat(5)); // hahahahaha</syntaxhighlight> |
||
As of ES6, `repeat` is built in, so this can be written as: |
As of ES6, `repeat` is built in, so this can be written as: |
||
< |
<syntaxhighlight lang="javascript"> |
||
console.log("ha".repeat(5)); // hahahahaha</ |
console.log("ha".repeat(5)); // hahahahaha</syntaxhighlight> |
||
====Repetition by Egyptian multiplication==== |
====Repetition by Egyptian multiplication==== |
||
Line 1,015: | Line 1,476: | ||
See the technique of 'Egyptian Multiplication' described in the Rhind Mathematical Papyrus at the British Museum. |
See the technique of 'Egyptian Multiplication' described in the Rhind Mathematical Papyrus at the British Museum. |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,033: | Line 1,494: | ||
return replicate(5000, "ha") |
return replicate(5000, "ha") |
||
})();</ |
})();</syntaxhighlight> |
||
====Concat . replicate==== |
====Concat . replicate==== |
||
Or, more generically, we could derive '''repeat''' as the composition of '''concat''' and '''replicate''' |
Or, more generically, we could derive '''repeat''' as the composition of '''concat''' and '''replicate''' |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 1,063: | Line 1,524: | ||
// TEST ------------------------------------------------------------------- |
// TEST ------------------------------------------------------------------- |
||
return repeat(5, 'ha'); |
return repeat(5, 'ha'); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
=={{header| |
=={{header|Joy}}== |
||
<syntaxhighlight lang="joy">DEFINE repeat == "" rotate [concat] cons times. |
|||
<lang jq>"a " * 3' # => "a a a "</lang> |
|||
"ha" 5 repeat.</syntaxhighlight> |
|||
Note that if the integer multiplicand is 0, then the result is null. |
|||
=={{header|jq}}== |
|||
<syntaxhighlight lang="jq">"a " * 3 # => "a a a "</syntaxhighlight> |
|||
Note that if the integer multiplicand is 0, then the result is the JSON value '''null'''. |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|1.0}} |
{{works with|Julia|1.0}} |
||
< |
<syntaxhighlight lang="julia">@show "ha" ^ 5 |
||
# The ^ operator is really just call to the `repeat` function |
# The ^ operator is really just call to the `repeat` function |
||
@show repeat("ha", 5)</ |
@show repeat("ha", 5)</syntaxhighlight> |
||
=={{header|K}}== |
=={{header|K}}== |
||
<syntaxhighlight lang="k"> |
|||
<lang k> |
|||
,/5#,"ha" |
,/5#,"ha" |
||
"hahahahaha" |
"hahahahaha" |
||
Line 1,088: | Line 1,553: | ||
5#"*" |
5#"*" |
||
"*****" |
"*****" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">fun main(args: Array<String>) { |
||
println("ha".repeat(5)) |
println("ha".repeat(5)) |
||
}</ |
}</syntaxhighlight> |
||
Or more fancy: |
Or more fancy: |
||
< |
<syntaxhighlight lang="scala">operator fun String.times(n: Int) = this.repeat(n) |
||
fun main(args: Array<String>) = println("ha" * 5)</ |
fun main(args: Array<String>) = println("ha" * 5)</syntaxhighlight> |
||
=={{header|LabVIEW}}== |
=={{header|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. |
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. |
||
[[file:LabVIEW_Repeat_a_string.png]] |
[[file:LabVIEW_Repeat_a_string.png]] |
||
<br/> |
|||
By using built in functions: |
|||
[[File:Panel.png]] |
|||
[[File:BlockDiagram.png]] |
|||
<br/> |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{S.map {lambda {_} ha} {S.serie 1 10}} |
|||
-> ha ha ha ha ha ha ha ha ha ha |
|||
or |
|||
{S.replace \s |
|||
by |
|||
in {S.map {lambda {_} ha} |
|||
{S.serie 1 10}}} |
|||
-> hahahahahahahahahaha |
|||
or |
|||
{def repeat |
|||
{lambda {:w :n} |
|||
{if {< :n 0} |
|||
then |
|||
else :w{repeat :w {- :n 1}}}}} |
|||
-> repeat |
|||
{repeat ha 10} |
|||
-> hahahahahahahahahahaha |
|||
</syntaxhighlight> |
|||
=={{header|Lang}}== |
|||
<syntaxhighlight lang="lang"> |
|||
# Repeat text function |
|||
fn.println(fn.repeatText(5, ha)) |
|||
# Output: hahahahaha |
|||
# Mul operator |
|||
fn.println(parser.op(ha * 5)) |
|||
# Output: hahahahaha |
|||
# Mul operator function |
|||
fn.println(fn.mul(ha, 5)) |
|||
# Output: hahahahaha |
|||
</syntaxhighlight> |
|||
=={{header|langur}}== |
|||
<syntaxhighlight lang="langur">"ha" * 5</syntaxhighlight> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
<lang |
<syntaxhighlight lang="lasso">'ha'*5 // hahahahaha</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lasso">loop(5) => {^ 'ha' ^} // hahahahaha</syntaxhighlight> |
||
=={{header|LFE}}== |
=={{header|LFE}}== |
||
< |
<syntaxhighlight lang="lisp"> |
||
(string:copies '"ha" 5) |
(string:copies '"ha" 5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">a$ ="ha " |
||
print StringRepeat$( a$, 5) |
print StringRepeat$( a$, 5) |
||
Line 1,125: | Line 1,640: | ||
next i |
next i |
||
StringRepeat$ =o$ |
StringRepeat$ =o$ |
||
end function</ |
end function</syntaxhighlight> |
||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
*Take a string and repeat it some number of times. |
*Take a string and repeat it some number of times. |
||
< |
<syntaxhighlight lang="lingo">on rep (str, n) |
||
res = "" |
res = "" |
||
repeat with i = 1 to n |
repeat with i = 1 to n |
||
Line 1,135: | Line 1,650: | ||
end repeat |
end repeat |
||
return res |
return res |
||
end</ |
end</syntaxhighlight> |
||
< |
<syntaxhighlight lang="lingo">put rep("ha", 5) |
||
-- "hahahahaha"</ |
-- "hahahahaha"</syntaxhighlight> |
||
*If there is a simpler/more efficient way to repeat a single “character”... |
*If there is a simpler/more efficient way to repeat a single “character”... |
||
< |
<syntaxhighlight lang="lingo">put bytearray(5, chartonum("*")).readRawString(5) |
||
-- "*****"</ |
-- "*****"</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">on mouseUp |
||
put repeatString("ha", 5) |
put repeatString("ha", 5) |
||
end mouseUp |
end mouseUp |
||
Line 1,152: | Line 1,667: | ||
end repeat |
end repeat |
||
return t |
return t |
||
end repeatString</ |
end repeatString</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to copies :n :thing [:acc "||] |
||
if :n = 0 [output :acc] |
if :n = 0 [output :acc] |
||
output (copies :n-1 :thing combine :acc :thing) |
output (copies :n-1 :thing combine :acc :thing) |
||
end</ |
end</syntaxhighlight> |
||
or using cascade: |
or using cascade: |
||
< |
<syntaxhighlight lang="logo">show cascade 5 [combine "ha ?] "|| ; hahahahaha</syntaxhighlight> |
||
Lhogho doesn't have cascade (yet), nor does it have the initialise a missing parameter capability demonstrated by the [:acc "||] above. |
Lhogho doesn't have cascade (yet), nor does it have the initialise a missing parameter capability demonstrated by the [:acc "||] above. |
||
< |
<syntaxhighlight lang="logo">to copies :n :thing :acc |
||
if :n = 0 [output :acc] |
if :n = 0 [output :acc] |
||
output (copies :n-1 :thing combine :acc :thing) |
output (copies :n-1 :thing combine :acc :thing) |
||
end |
end |
||
print copies 5 "ha "||</ |
print copies 5 "ha "||</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end</syntaxhighlight> |
||
Or use native string library function |
Or use native string library function |
||
<lang |
<syntaxhighlight lang="lua">string.rep(s,n)</syntaxhighlight> |
||
=={{header|Maple}}== |
=={{header|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. |
There are many ways to do this in Maple. First, the "right" (most efficient) way is to use the supplied procedures for this purpose. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> use StringTools in |
> use StringTools in |
||
> Repeat( "abc", 10 ); # repeat an arbitrary string |
> Repeat( "abc", 10 ); # repeat an arbitrary string |
||
Line 1,187: | Line 1,702: | ||
"xxxxxxxxxxxxxxxxxxxx" |
"xxxxxxxxxxxxxxxxxxxx" |
||
</syntaxhighlight> |
|||
</lang> |
|||
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. |
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. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> cat( "abc" $ 10 ); |
> cat( "abc" $ 10 ); |
||
"abcabcabcabcabcabcabcabcabcabc" |
"abcabcabcabcabcabcabcabcabcabc" |
||
Line 1,195: | Line 1,710: | ||
> cat( seq( "abc", i = 1 .. 10 ) ); |
> cat( seq( "abc", i = 1 .. 10 ) ); |
||
"abcabcabcabcabcabcabcabcabcabc" |
"abcabcabcabcabcabcabcabcabcabc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
You ''can'' build up a string in a loop, but this is highly inefficient (quadratic); don't do this. |
You ''can'' build up a string in a loop, but this is highly inefficient (quadratic); don't do this. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> s := "": |
> s := "": |
||
> to 10 do s := cat( s, "abc" ) end: s; |
> to 10 do s := cat( s, "abc" ) end: s; |
||
"abcabcabcabcabcabcabcabcabcabc" |
"abcabcabcabcabcabcabcabcabcabc" |
||
</syntaxhighlight> |
|||
</lang> |
|||
If you need to build up a string incrementally, use a StringBuffer object, which keeps things linear. |
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. |
Finally, note that strings and characters are not distinct datatypes in Maple; a character is just a string of length one. |
||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
<syntaxhighlight lang="mathematica">StringRepeat["ha", 5]</syntaxhighlight> |
|||
<lang 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]</lang> |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
< |
<syntaxhighlight lang="matlab">function S = repeat(s , n) |
||
S = repmat(s , [1,n]) ; |
S = repmat(s , [1,n]) ; |
||
return</ |
return</syntaxhighlight> |
||
Note 1: The repetition is returned, not displayed. |
Note 1: The repetition is returned, not displayed. |
||
Line 1,226: | Line 1,734: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">"$*"(s, n) := apply(sconcat, makelist(s, n))$ |
||
infix("$*")$ |
infix("$*")$ |
||
"abc" $* 5; |
"abc" $* 5; |
||
/* "abcabcabcabcabc" */</ |
/* "abcabcabcabcabc" */</syntaxhighlight> |
||
=={{header|Mercury}}== |
=={{header|Mercury}}== |
||
Mercury's 'string' module provides an efficient char-repeater. The following uses string.builder to repeat strings. |
Mercury's 'string' module provides an efficient char-repeater. The following uses string.builder to repeat strings. |
||
< |
<syntaxhighlight lang="mercury">:- module repeat. |
||
:- interface. |
:- interface. |
||
:- import_module string, char, int. |
:- import_module string, char, int. |
||
Line 1,260: | Line 1,768: | ||
print(Stream, String, !S), |
print(Stream, String, !S), |
||
printn(Stream, N - 1, String, !S) |
printn(Stream, N - 1, String, !S) |
||
; true ).</ |
; true ).</syntaxhighlight> |
||
=={{header|min}}== |
=={{header|min}}== |
||
{{works with|min|0.19.3}} |
{{works with|min|0.19.3}} |
||
< |
<syntaxhighlight lang="min">"ha" 5 repeat print</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,271: | Line 1,779: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
< |
<syntaxhighlight lang="miniscript">str = "Lol" |
||
print str * 5</ |
print str * 5</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,279: | Line 1,787: | ||
=={{header|Mirah}}== |
=={{header|Mirah}}== |
||
< |
<syntaxhighlight lang="mirah">x = StringBuilder.new |
||
5.times do |
5.times do |
||
Line 1,285: | Line 1,793: | ||
end |
end |
||
puts x # ==> "hahahahaha"</ |
puts x # ==> "hahahahaha"</syntaxhighlight> |
||
=={{header|Monte}}== |
=={{header|Monte}}== |
||
<syntaxhighlight lang="monte"> |
|||
<lang Monte> |
|||
var s := "ha " * 5 |
var s := "ha " * 5 |
||
traceln(s) |
traceln(s) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|MontiLang}}== |
=={{header|MontiLang}}== |
||
<lang |
<syntaxhighlight lang="montilang">|ha| 5 * PRINT .</syntaxhighlight> |
||
Or with a loop |
Or with a loop |
||
< |
<syntaxhighlight lang="montilang">FOR 5 |
||
|ha| OUT . |
|ha| OUT . |
||
ENDFOR || PRINT .</ |
ENDFOR || PRINT .</syntaxhighlight> |
||
Or ... |
Or ... |
||
< |
<syntaxhighlight lang="montilang">|ha| FOR 5 OUT ENDFOR . || PRINT .</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
< |
<syntaxhighlight lang="mumps">RPTSTR(S,N) |
||
;Repeat a string S for N times |
;Repeat a string S for N times |
||
NEW I |
NEW I |
||
Line 1,314: | Line 1,822: | ||
F I=1:1:N W S |
F I=1:1:N W S |
||
Q |
Q |
||
</syntaxhighlight> |
|||
</lang> |
|||
This last example uses the [http://docs.intersystems.com/cache20121/csp/docbook/DocBook.UI.Page.cls?KEY=RCOS_fpiece#RCOS_B57001 $PIECE] function. |
This last example uses the [http://docs.intersystems.com/cache20121/csp/docbook/DocBook.UI.Page.cls?KEY=RCOS_fpiece#RCOS_B57001 $PIECE] function. |
||
<syntaxhighlight lang="mumps"> |
|||
<lang MUMPS> |
|||
;Even better (more terse) |
;Even better (more terse) |
||
S x="",$P(x,"-",10)="-" |
S x="",$P(x,"-",10)="-" |
||
W x |
W x |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nanoquery}}== |
=={{header|Nanoquery}}== |
||
In Nanoquery, multiplying strings by an integer returns a new string with the original value repeated. |
In Nanoquery, multiplying strings by an integer returns a new string with the original value repeated. |
||
< |
<syntaxhighlight lang="nanoquery">"ha" * 5</syntaxhighlight> |
||
=={{header|Neko}}== |
=={{header|Neko}}== |
||
< |
<syntaxhighlight lang="actionscript">/* Repeat a string, in Neko */ |
||
var srep = function(s, n) { |
var srep = function(s, n) { |
||
var str = "" |
var str = "" |
||
Line 1,339: | Line 1,847: | ||
} |
} |
||
$print(srep("ha", 5), "\n")</ |
$print(srep("ha", 5), "\n")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,348: | Line 1,856: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
Any of the methods shown in the [[Repeat_a_string#C.23|C#]] solution would also work for Nemerle, but they're all semantically awkward. This example uses an extension method to wrap one of the awkward techniques in order to clarify the semantics (which is also possible in C#, there's nothing really Nemerle specific here except the syntax). |
Any of the methods shown in the [[Repeat_a_string#C.23|C#]] solution would also work for Nemerle, but they're all semantically awkward. This example uses an extension method to wrap one of the awkward techniques in order to clarify the semantics (which is also possible in C#, there's nothing really Nemerle specific here except the syntax). |
||
< |
<syntaxhighlight lang="nemerle">using System; |
||
using System.Console; |
using System.Console; |
||
Line 1,365: | Line 1,873: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
NetRexx has built in functions to manipulate strings. The most appropriate for this task is the <code>'''copies()'''</code> function: |
NetRexx has built in functions to manipulate strings. The most appropriate for this task is the <code>'''copies()'''</code> function: |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
ha5 = 'ha'.copies(5) |
ha5 = 'ha'.copies(5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
There are several other built-in functions that can be used to achieve the same result depending on need: |
There are several other built-in functions that can be used to achieve the same result depending on need: |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
sampleStr = 'ha' -- string to duplicate |
sampleStr = 'ha' -- string to duplicate |
||
say ' COPIES:' sampleStr.copies(5) |
say ' COPIES:' sampleStr.copies(5) |
||
Line 1,388: | Line 1,896: | ||
say ' SUBSTR:' ''.substr(1, 5, sampleChr) |
say ' SUBSTR:' ''.substr(1, 5, sampleChr) |
||
say 'TRANSLATE:' '.....'.translate(sampleChr, '.') |
say 'TRANSLATE:' '.....'.translate(sampleChr, '.') |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|NewLISP}}== |
=={{header|NewLISP}}== |
||
< |
<syntaxhighlight lang="newlisp">(dup "ha" 5)</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<syntaxhighlight lang="nim">import strutils |
|||
<lang nim> |
|||
import strutils |
|||
# Repeat a char. |
|||
repeat("ha", 5) |
|||
echo repeat('a', 5) # -> "aaaaa". |
|||
</lang> |
|||
# Repeat a string. |
|||
echo repeat("ha", 5) # -> "hahahahaha".</syntaxhighlight> |
|||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">bundle Default { |
||
class Repeat { |
class Repeat { |
||
function : Main(args : String[]) ~ Nil { |
function : Main(args : String[]) ~ Nil { |
||
Line 1,415: | Line 1,926: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
Line 1,424: | Line 1,935: | ||
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. |
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. |
||
< |
<syntaxhighlight lang="objc">@interface NSString (RosettaCodeAddition) |
||
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times; |
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times; |
||
@end |
@end |
||
Line 1,432: | Line 1,943: | ||
return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0]; |
return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0]; |
||
} |
} |
||
@end</ |
@end</syntaxhighlight> |
||
Now, let's put it to use: |
Now, let's put it to use: |
||
< |
<syntaxhighlight lang="objc"> // Instantiate an NSString by sending an NSString literal our new |
||
// -repeatByNumberOfTimes: selector. |
// -repeatByNumberOfTimes: selector. |
||
NSString *aString = [@"ha" repeatStringByNumberOfTimes:5]; |
NSString *aString = [@"ha" repeatStringByNumberOfTimes:5]; |
||
// Display the NSString. |
// Display the NSString. |
||
NSLog(@"%@", aString);</ |
NSLog(@"%@", aString);</syntaxhighlight> |
||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
Since Ocaml 4.02 strings are immutable, as is convenient for a functional language. Mutable strings are now implemented in the module Bytes. |
Since Ocaml 4.02 strings are immutable, as is convenient for a functional language. Mutable strings are now implemented in the module Bytes. |
||
< |
<syntaxhighlight lang="ocaml">let string_repeat s n = |
||
let s = Bytes.of_string s in |
|||
let len = Bytes.length s in |
let len = Bytes.length s in |
||
let res = Bytes.create(n * len) in |
let res = Bytes.create (n * len) in |
||
for i = 0 to pred n do |
for i = 0 to pred n do |
||
Bytes.blit s 0 res (i * len) len |
Bytes.blit s 0 res (i * len) len |
||
done; |
done; |
||
Bytes.to_string res |
(Bytes.to_string res) |
||
;;</ |
;;</syntaxhighlight> |
||
which gives the signature< |
which gives the signature<syntaxhighlight lang="ocaml">val string_repeat : string -> int -> string = <fun></syntaxhighlight> |
||
testing in the toplevel: |
testing in the toplevel: |
||
< |
<syntaxhighlight lang="ocaml"># string_repeat "Hiuoa" 3 ;; |
||
- : string = "HiuoaHiuoaHiuoa"</ |
- : string = "HiuoaHiuoaHiuoa"</syntaxhighlight> |
||
Alternately create an array initialized to s, and concat: |
Alternately create an array initialized to s, and concat: |
||
< |
<syntaxhighlight lang="ocaml">let string_repeat s n = |
||
String.concat "" (Array.to_list (Array.make n s)) |
String.concat "" (Array.to_list (Array.make n s)) |
||
;;</ |
;;</syntaxhighlight> |
||
Or: |
Or: |
||
< |
<syntaxhighlight lang="ocaml">let string_repeat s n = |
||
Array.fold_left (^) "" (Array.make n s) |
Array.fold_left (^) "" (Array.make n s) |
||
;;</ |
;;</syntaxhighlight> |
||
To repeat a single character use: |
To repeat a single character use: |
||
<lang |
<syntaxhighlight lang="ocaml">String.make 5 '*'</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">StringBuffer new "abcd" <<n(5)</syntaxhighlight> |
||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
< |
<syntaxhighlight lang="progress (openedge abl)">MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.</syntaxhighlight> |
||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
'REPEATING A CHARACTER |
'REPEATING A CHARACTER |
||
Line 1,498: | Line 2,010: | ||
print RepeatString "ABC",3 'result ABCABCABC |
print RepeatString "ABC",3 'result ABCABCABC |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
We have to write a function for this: |
We have to write a function for this: |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {Repeat Xs N} |
fun {Repeat Xs N} |
||
if N > 0 then |
if N > 0 then |
||
Line 1,511: | Line 2,023: | ||
end |
end |
||
in |
in |
||
{System.showInfo {Repeat "Ha" 5}}</ |
{System.showInfo {Repeat "Ha" 5}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
===Version #1. Based on recursion.=== |
===Version #1. Based on recursion.=== |
||
This solution is recursive and 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|C]]) and pass that to GP. |
This solution is recursive and 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|C]]) and pass that to GP. |
||
< |
<syntaxhighlight lang="parigp">repeat(s,n)={ |
||
if(n, Str(repeat(s, n-1), s), "") |
if(n, Str(repeat(s, n-1), s), "") |
||
};</ |
};</syntaxhighlight> |
||
<code>concat()</code> joins together a vector of strings, in this case a single string repeated. |
<code>concat()</code> joins together a vector of strings, in this case a single string repeated. |
||
< |
<syntaxhighlight lang="parigp">repeat(s,n)=concat(vector(n,i, s));</syntaxhighlight> |
||
This solution is recursive and slightly less bad than the others for large n. |
This solution is recursive and slightly less bad than the others for large n. |
||
< |
<syntaxhighlight lang="parigp">repeat(s,n)={ |
||
if(n<4, return(concat(vector(n,i, s)))); |
if(n<4, return(concat(vector(n,i, s)))); |
||
if(n%2, |
if(n%2, |
||
Line 1,531: | Line 2,043: | ||
repeat(Str(s,s),n\2) |
repeat(Str(s,s),n\2) |
||
); |
); |
||
}</ |
}</syntaxhighlight> |
||
===Version #2. Simple loop based.=== |
===Version #2. Simple loop based.=== |
||
Line 1,539: | Line 2,051: | ||
for the heavy text processing. |
for the heavy text processing. |
||
< |
<syntaxhighlight lang="parigp"> |
||
\\ Repeat a string str the specified number of times ntimes and return composed string. |
\\ Repeat a string str the specified number of times ntimes and return composed string. |
||
\\ 3/3/2016 aev |
\\ 3/3/2016 aev |
||
Line 1,560: | Line 2,072: | ||
print1("6."); for(i=1,10000000, srepeat("e",10)); |
print1("6."); for(i=1,10000000, srepeat("e",10)); |
||
} |
} |
||
</ |
</syntaxhighlight> |
||
{{Output}} |
{{Output}} |
||
Line 1,577: | Line 2,089: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
See [[#Delphi|Delphi]] or [[#Free Pascal|Free Pascal]], as standard Pascal does not know strings of unlimited length. |
See [[#Delphi|Delphi]] or [[#Free Pascal|Free Pascal]], as standard Pascal does not know strings of unlimited length. |
||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
Print('ha' * 5) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hahahahaha |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">"ha" x 5</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--<syntaxhighlight lang="phix">(phixonline)--> |
|||
<lang Phix>?repeat('*',5) |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'*'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span> |
|||
?join(repeat("ha",5),"")</lang> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ha"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span><span style="color: #008000;">""</span><span style="color: #0000FF;">)</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,591: | Line 2,116: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">def rep /# s n -- s #/ |
||
"" swap |
|||
for drop |
|||
over chain |
|||
drop |
|||
endfor |
|||
over chain |
|||
nip |
|||
endfor |
|||
nip |
|||
enddef |
enddef |
||
"ha" 5 rep print</ |
"ha" 5 rep print</syntaxhighlight> |
||
Same result (simple character): |
|||
<syntaxhighlight lang="phixmonti">65 5 rep |
|||
65 5 repeat |
|||
'A' 5 repeat</syntaxhighlight> |
|||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php">str_repeat("ha", 5)</syntaxhighlight> |
||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(pack (need 5 "ha")) |
||
-> "hahahahaha"</ |
-> "hahahahaha"</syntaxhighlight> |
||
or: |
or: |
||
< |
<syntaxhighlight lang="picolisp">(pack (make (do 5 (link "ha")))) |
||
-> "hahahahaha"</ |
-> "hahahahaha"</syntaxhighlight> |
||
=={{header|Pike}}== |
=={{header|Pike}}== |
||
< |
<syntaxhighlight lang="pike">"ha"*5;</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
/* To repeat a string a variable number of times: */ |
/* To repeat a string a variable number of times: */ |
||
Line 1,628: | Line 2,156: | ||
s = (5)'h'; /* asigns 'hhhhh' to s. */ |
s = (5)'h'; /* asigns 'hhhhh' to s. */ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Plain English}}== |
|||
<syntaxhighlight lang="plainenglish">To run: |
|||
Start up. |
|||
Put "ha" into a string. |
|||
Append the string to itself given 5. |
|||
Write the string on the console. |
|||
Fill another string with the asterisk byte given 5. |
|||
Write the other string on the console. |
|||
Wait for the escape key. |
|||
Shut down. |
|||
To append a string to itself given a number: |
|||
If the number is less than 1, exit. |
|||
Privatize the string. |
|||
Privatize the number. |
|||
Subtract 1 from the number. |
|||
Append the string to the original string given the number.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hahahahaha |
|||
***** |
|||
</pre> |
|||
=={{header|Plorth}}== |
=={{header|Plorth}}== |
||
< |
<syntaxhighlight lang="plorth">"ha" 5 *</syntaxhighlight> |
||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
< |
<syntaxhighlight lang="postscript">% the comments show the stack content after the line was executed |
||
% where rcount is the repeat count, "o" is for orignal, |
% where rcount is the repeat count, "o" is for orignal, |
||
% "f" is for final, and iter is the for loop variable |
% "f" is for final, and iter is the for loop variable |
||
Line 1,652: | Line 2,203: | ||
} for |
} for |
||
pop % fstring |
pop % fstring |
||
} def</ |
} def</syntaxhighlight> |
||
=={{header|PowerBASIC}}== |
=={{header|PowerBASIC}}== |
||
< |
<syntaxhighlight lang="powerbasic">MSGBOX REPEAT$(5, "ha")</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">"ha" * 5 # ==> "hahahahaha"</syntaxhighlight> |
||
=={{header|Processing}}== |
=={{header|Processing}}== |
||
< |
<syntaxhighlight lang="processing">void setup() { |
||
String rep = repeat("ha", 5); |
String rep = repeat("ha", 5); |
||
println(rep); |
println(rep); |
||
Line 1,670: | Line 2,221: | ||
// and return as a new String |
// and return as a new String |
||
return new String(new char[times]).replace("\0", str); |
return new String(new char[times]).replace("\0", str); |
||
}</ |
}</syntaxhighlight> |
||
==={{header|Processing Python mode}}=== |
==={{header|Processing Python mode}}=== |
||
< |
<syntaxhighlight lang="python">def setup(): |
||
rep = repeat("ha", 5) |
rep = repeat("ha", 5) |
||
println(rep) |
println(rep) |
||
def repeat(s, times): |
def repeat(s, times): |
||
return s * times</ |
return s * times</syntaxhighlight> |
||
=={{header|Python}}== |
|||
<lang python>def repeat(s, times): |
|||
return s * times |
|||
print(repeat("ha", 5))</lang> |
|||
# output: |
|||
# hahahahaha |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
< |
<syntaxhighlight lang="prolog">%repeat(Str,Num,Res). |
||
repeat(Str,1,Str). |
repeat(Str,1,Str). |
||
repeat(Str,Num,Res):- |
repeat(Str,Num,Res):- |
||
Num1 is Num-1, |
Num1 is Num-1, |
||
repeat(Str,Num1,Res1), |
repeat(Str,Num1,Res1), |
||
string_concat(Str, Res1, Res).</ |
string_concat(Str, Res1, Res).</syntaxhighlight> |
||
=== alternative using DCG strings === |
|||
This tail-recursive DCG implemention |
|||
is more efficient than anything using lists:append . |
|||
{{works with|SWI-Prolog|7}} |
|||
<syntaxhighlight lang="prolog"> |
|||
:- system:set_prolog_flag(double_quotes,chars) . |
|||
repeat(SOURCEz0,COUNT0,TARGETz) |
|||
:- |
|||
prolog:phrase(repeat(SOURCEz0,COUNT0),TARGETz) |
|||
. |
|||
%! repeat(SOURCEz0,COUNT0)//2 |
|||
repeat(_SOURCEz0_,0) |
|||
--> |
|||
! , |
|||
[] |
|||
. |
|||
repeat(SOURCEz0,COUNT0) |
|||
--> |
|||
SOURCEz0 , |
|||
{ COUNT is COUNT0 - 1 } , |
|||
repeat(SOURCEz0,COUNT) |
|||
. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
/* |
|||
?- repeat("ha",5,TARGETz) . |
|||
TARGETz = [h, a, h, a, h, a, h, a, h, a]. |
|||
?- |
|||
*/ |
|||
</pre> |
|||
<pre> |
|||
:- begin_tests(basic) . |
|||
:- system:set_prolog_flag(double_quotes,chars) . |
|||
test('1',[]) |
|||
:- |
|||
repeat("a",2,"aa") |
|||
. |
|||
test('2',[]) |
|||
:- |
|||
repeat("ha",2,"haha") |
|||
. |
|||
test('3',[]) |
|||
:- |
|||
repeat("ha",3,"hahaha") |
|||
. |
|||
test('4',[]) |
|||
:- |
|||
repeat("",3,"") |
|||
. |
|||
test('5',[]) |
|||
:- |
|||
repeat("ha",0,"") |
|||
. |
|||
test('6',[]) |
|||
:- |
|||
repeat("ha",1,"ha") |
|||
. |
|||
:- end_tests(basic) . |
|||
</pre> |
|||
=={{header|Pure}}== |
=={{header|Pure}}== |
||
Line 1,700: | Line 2,323: | ||
repeating it more than 0 times results in the concatenation of the string and (n-1) further repeats. |
repeating it more than 0 times results in the concatenation of the string and (n-1) further repeats. |
||
< |
<syntaxhighlight lang="pure">> str_repeat 0 s = ""; |
||
> str_repeat n s = s + (str_repeat (n-1) s) if n>0; |
> str_repeat n s = s + (str_repeat (n-1) s) if n>0; |
||
> str_repeat 5 "ha"; |
> str_repeat 5 "ha"; |
||
"hahahahaha" |
"hahahahaha" |
||
></ |
></syntaxhighlight> |
||
You can define str_repeat using infinite lazy list (stream). |
You can define str_repeat using infinite lazy list (stream). |
||
< |
<syntaxhighlight lang="pure"> |
||
str_repeat n::int s::string = string $ take n $ cycle (s:[]); |
str_repeat n::int s::string = string $ take n $ cycle (s:[]); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
< |
<syntaxhighlight lang="purebasic">Procedure.s RepeatString(count, text$=" ") |
||
Protected i, ret$="" |
Protected i, ret$="" |
||
Line 1,722: | Line 2,345: | ||
EndProcedure |
EndProcedure |
||
Debug RepeatString(5, "ha")</ |
Debug RepeatString(5, "ha")</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">"ha" * 5 # ==> "hahahahaha"</syntaxhighlight> |
||
"Characters" are just strings of length one. |
"Characters" are just strings of length one. |
||
the other way also works: |
the other way also works: |
||
< |
<syntaxhighlight lang="python">5 * "ha" # ==> "hahahahaha"</syntaxhighlight> |
||
=== Using a Function === |
|||
<syntaxhighlight lang="python">def repeat(s, times): |
|||
return s * times |
|||
print(repeat("ha", 5))</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>hahahahaha</pre> |
|||
=== Using Lambda === |
|||
<syntaxhighlight lang="python">x = lambda a: a * 5 |
|||
print(x("ha"))</syntaxhighlight> |
|||
{{Out}} |
|||
<pre>hahahahaha</pre> |
|||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery">$ "ha" 5 of echo$</syntaxhighlight> |
|||
'''Output:''' |
|||
<pre>hahahahaha</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="ruby">strrep("ha", 5)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
< |
<syntaxhighlight lang="racket"> |
||
#lang racket |
#lang racket |
||
;; fast |
;; fast |
||
Line 1,741: | Line 2,383: | ||
(string-append* (make-list n str))) |
(string-append* (make-list n str))) |
||
(string-repeat 5 "ha") ; => "hahahahaha" |
(string-repeat 5 "ha") ; => "hahahahaha" |
||
</syntaxhighlight> |
|||
</lang> |
|||
To repeat a single character: |
To repeat a single character: |
||
< |
<syntaxhighlight lang="racket"> |
||
(make-string 5 #\*) => "*****" |
(make-string 5 #\*) => "*****" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>print "ha" x 5</syntaxhighlight> |
||
(Note that the <code>x</code> operator isn't quite the same as in Perl 5: it now only creates strings. To create lists, use <code>xx</code>.) |
(Note that the <code>x</code> operator isn't quite the same as in Perl 5: it now only creates strings. To create lists, use <code>xx</code>.) |
||
=={{header|RapidQ}}== |
=={{header|RapidQ}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
'For a single char |
'For a single char |
||
showmessage String$(10, "-") |
showmessage String$(10, "-") |
||
Line 1,767: | Line 2,409: | ||
showmessage Repeat$("ha", 5) |
showmessage Repeat$("ha", 5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REALbasic}}== |
=={{header|REALbasic}}== |
||
< |
<syntaxhighlight lang="vb">Function Repeat(s As String, count As Integer) As String |
||
Dim output As String |
Dim output As String |
||
For i As Integer = 0 To count |
For i As Integer = 0 To count |
||
Line 1,777: | Line 2,419: | ||
Return output |
Return output |
||
End Function |
End Function |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|REBOL}}== |
=={{header|REBOL}}== |
||
< |
<syntaxhighlight lang="rebol">head insert/dup "" "ha" 5</syntaxhighlight> |
||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="red">>> str: "Add duplicates to string" |
||
>> insert/dup str "ha" 3 |
>> insert/dup str "ha" 3 |
||
== "hahahaAdd duplicates to string" |
== "hahahaAdd duplicates to string" |
||
>> insert/dup tail str "ha" 3 |
>> insert/dup tail str "ha" 3 |
||
== "hahahaAdd duplicates to stringhahaha"</ |
== "hahahaAdd duplicates to stringhahaha"</syntaxhighlight> |
||
=={{header|ReScript}}== |
|||
<syntaxhighlight lang="rescript">Js.log(Js.String2.repeat("ha", 5))</syntaxhighlight> |
|||
=={{header|Retro}}== |
=={{header|Retro}}== |
||
< |
<syntaxhighlight lang="retro">with strings' |
||
: repeatString ( $n-$ ) |
: repeatString ( $n-$ ) |
||
1- [ dup ] dip [ over prepend ] times nip ; |
1- [ dup ] dip [ over prepend ] times nip ; |
||
"ha" 5 repeatString</ |
"ha" 5 repeatString</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Since the REXX language only supports the "character" type, it's not surprising that there are so many ways to skin a cat. |
Since the REXX language only supports the "character" type, it's not surprising that there are so many ways to skin a cat. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program to show various ways to repeat a string (or repeat a single char).*/ |
||
/*all examples are equivalent, but not created equal.*/ |
/*all examples are equivalent, but not created equal.*/ |
||
Line 1,915: | Line 2,560: | ||
parse value y||y||y||y||y with z |
parse value y||y||y||y||y with z |
||
exit /*stick a fork in it, we're done.*/</ |
exit /*stick a fork in it, we're done.*/</syntaxhighlight> |
||
Some older REXXes don't have a '''changestr''' bif, so one is included here ──► [[CHANGESTR.REX]]. |
Some older REXXes don't have a '''changestr''' bif, so one is included here ──► [[CHANGESTR.REX]]. |
||
<br><br> |
<br><br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> Copy("ha" , 5) # ==> "hahahahaha"</syntaxhighlight> |
||
=={{header|RPL}}== |
|||
≪ "" 1 5 START "ha" + NEXT ≫ EVAL |
|||
{{out}} |
|||
<pre>1: "hahahahaha"</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
< |
<syntaxhighlight lang="ruby">"ha" * 5 # ==> "hahahahaha"</syntaxhighlight> |
||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">a$ = "ha " |
||
for i = 1 to 5 |
for i = 1 to 5 |
||
a1$ = a1$ + a$ |
a1$ = a1$ + a$ |
||
next i |
next i |
||
a$ = a1$ |
a$ = a1$ |
||
print a$</ |
print a$</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">std::iter::repeat("ha").take(5).collect::<String>(); // ==> "hahahahaha"</syntaxhighlight> |
||
Since 1.16: |
Since 1.16: |
||
< |
<syntaxhighlight lang="rust">"ha".repeat(5); // ==> "hahahahaha"</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala">"ha" * 5 // ==> "hahahahaha"</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (string-repeat n str) |
||
(apply string-append (vector->list (make-vector n str))))</ |
(apply string-append (vector->list (make-vector n str))))</syntaxhighlight> |
||
with SRFI 1: |
with SRFI 1: |
||
< |
<syntaxhighlight lang="scheme">(define (string-repeat n str) |
||
(fold string-append "" (make-list n str))) |
(fold string-append "" (make-list n str))) |
||
(string-repeat 5 "ha") ==> "hahahahaha"</ |
(string-repeat 5 "ha") ==> "hahahahaha"</syntaxhighlight> |
||
To repeat a single character: |
To repeat a single character: |
||
< |
<syntaxhighlight lang="scheme">(make-string 5 #\*)</syntaxhighlight> |
||
=={{header|Scratch}}== |
=={{header|Scratch}}== |
||
Line 1,960: | Line 2,609: | ||
=={{header|sed}}== |
=={{header|sed}}== |
||
Number of ampersands indicates number of repetitions. |
Number of ampersands indicates number of repetitions. |
||
< |
<syntaxhighlight lang="sed"> |
||
$ echo ha | sed 's/.*/&&&&&/' |
$ echo ha | sed 's/.*/&&&&&/' |
||
hahahahaha |
hahahahaha |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
begin |
begin |
||
writeln("ha" mult 5); |
writeln("ha" mult 5); |
||
end func;</ |
end func;</syntaxhighlight> |
||
Output: |
Output: |
||
Line 1,979: | Line 2,628: | ||
=={{header|SenseTalk}}== |
=={{header|SenseTalk}}== |
||
< |
<syntaxhighlight lang="sensetalk"> |
||
put "Ho!" repeated 3 times |
put "Ho!" repeated 3 times |
||
put "Merry" repeated to length 12 |
put "Merry" repeated to length 12 |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,991: | Line 2,640: | ||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">'ha' * 5; # ==> 'hahahahaha'</syntaxhighlight> |
||
=={{header|Sinclair ZX81 BASIC}}== |
=={{header|Sinclair ZX81 BASIC}}== |
||
Works with 1k of RAM. This program defines a subroutine that expects to find a string and a number of times to repeat it; but all it then does is loop and concatenate, so making it a separate subroutine is arguably overkill. |
Works with 1k of RAM. This program defines a subroutine that expects to find a string and a number of times to repeat it; but all it then does is loop and concatenate, so making it a separate subroutine is arguably overkill. |
||
< |
<syntaxhighlight lang="basic"> 10 LET S$="HA" |
||
20 LET N=5 |
20 LET N=5 |
||
30 GOSUB 60 |
30 GOSUB 60 |
||
Line 2,004: | Line 2,653: | ||
80 LET T$=T$+S$ |
80 LET T$=T$+S$ |
||
90 NEXT I |
90 NEXT I |
||
100 RETURN</ |
100 RETURN</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
If n is a small constant, then simply concatenating n times will do; for example, n=5:: |
If n is a small constant, then simply concatenating n times will do; for example, n=5:: |
||
< |
<syntaxhighlight lang="smalltalk">v := 'ha'. |
||
v,v,v,v,v</ |
v,v,v,v,v</syntaxhighlight> |
||
{{works with|Pharo|1.4}} |
{{works with|Pharo|1.4}} |
||
Line 2,017: | Line 2,666: | ||
By creating a collection of n 'ha', and joining them to a string: |
By creating a collection of n 'ha', and joining them to a string: |
||
< |
<syntaxhighlight lang="smalltalk">((1 to: n) collect: [:x | 'ha']) joinUsing: ''.</syntaxhighlight> |
||
or:{{works with|Smalltalk/X}} |
or:{{works with|Smalltalk/X}} |
||
{{works with|VisualWorks Smalltalk}} |
{{works with|VisualWorks Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">(Array new:n withAll:'ha') asStringWith:''.</syntaxhighlight> |
||
By creating a WriteStream, and putting N times the string 'ha' into it: |
By creating a WriteStream, and putting N times the string 'ha' into it: |
||
< |
<syntaxhighlight lang="smalltalk">ws := '' writeStream. |
||
n timesRepeat: [ws nextPutAll: 'ha']. |
n timesRepeat: [ws nextPutAll: 'ha']. |
||
ws contents.</ |
ws contents.</syntaxhighlight> |
||
alternatively: |
alternatively: |
||
< |
<syntaxhighlight lang="smalltalk">(String streamContents:[:ws | n timesRepeat: [ws nextPutAll: 'ha']])</syntaxhighlight> |
||
all evaluate to: |
all evaluate to: |
||
Line 2,036: | Line 2,685: | ||
A string containing a repeated character is generated with: |
A string containing a repeated character is generated with: |
||
<lang |
<syntaxhighlight lang="smalltalk">String new:n withAll:$*</syntaxhighlight> |
||
{{works with|VA Smalltalk}} |
{{works with|VA Smalltalk}} |
||
< |
<syntaxhighlight lang="smalltalk">(String new:n) atAllPut:$*</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
< |
<syntaxhighlight lang="snobol4"> output = dupl("ha",5) |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Sparkling}}== |
=={{header|Sparkling}}== |
||
< |
<syntaxhighlight lang="sparkling">spn:3> repeat("na", 8) .. " Batman!" |
||
= nananananananana Batman!</ |
= nananananananana Batman!</syntaxhighlight> |
||
=={{header|SQL}}== |
=={{header|SQL}}== |
||
< |
<syntaxhighlight lang="sql">select rpad('', 10, 'ha')</syntaxhighlight> |
||
=={{header|SQL PL}}== |
=={{header|SQL PL}}== |
||
{{works with|Db2 LUW}} |
{{works with|Db2 LUW}} |
||
< |
<syntaxhighlight lang="sql pl"> |
||
VALUES REPEAT('ha', 5); |
VALUES REPEAT('ha', 5); |
||
VALUES RPAD('', 10, 'ha'); |
VALUES RPAD('', 10, 'ha'); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,079: | Line 2,728: | ||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">fun string_repeat (s, n) = |
||
concat (List.tabulate (n, fn _ => s)) |
concat (List.tabulate (n, fn _ => s)) |
||
;</ |
;</syntaxhighlight> |
||
testing in the interpreter: |
testing in the interpreter: |
||
< |
<syntaxhighlight lang="sml">- string_repeat ("Hiuoa", 3) ; |
||
val it = "HiuoaHiuoaHiuoa" : string</ |
val it = "HiuoaHiuoaHiuoa" : string</syntaxhighlight> |
||
To repeat a single character: |
To repeat a single character: |
||
< |
<syntaxhighlight lang="sml">fun char_repeat (c, n) = |
||
implode (List.tabulate (n, fn _ => c)) |
implode (List.tabulate (n, fn _ => c)) |
||
;</ |
;</syntaxhighlight> |
||
=={{header|Stata}}== |
=={{header|Stata}}== |
||
< |
<syntaxhighlight lang="stata">. scalar a="ha" |
||
. scalar b=a*5 |
. scalar b=a*5 |
||
. display b |
. display b |
||
hahahahaha</ |
hahahahaha</syntaxhighlight> |
||
=={{header|Suneido}}== |
=={{header|Suneido}}== |
||
< |
<syntaxhighlight lang="suneido">'ha'.Repeat(5) --> "hahahahaha" |
||
'*'.Repeat(5) --> "*****"</ |
'*'.Repeat(5) --> "*****"</syntaxhighlight> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
=== The Builtin Way === |
|||
<syntaxhighlight lang="swift">print(String(repeating:"*", count: 5))</syntaxhighlight> |
|||
{{out}}***** |
|||
=== Functions === |
|||
<syntaxhighlight lang="swift">func * (left:String, right:Int) -> String { |
|||
return String(repeating:left, count:right) |
|||
} |
|||
print ("HA" * 5) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
HAHAHAHAHA |
|||
=== Extensions === |
|||
Using extensions to do the repetition which makes for an easier syntax when repeating Strings, and using String.extend() to get faster evaluation. |
Using extensions to do the repetition which makes for an easier syntax when repeating Strings, and using String.extend() to get faster evaluation. |
||
< |
<syntaxhighlight lang="swift">extension String { |
||
// Slower version |
// Slower version |
||
func repeatString(n: Int) -> String { |
func repeatString(n: Int) -> String { |
||
Line 2,123: | Line 2,791: | ||
print( "ha".repeatString(5) ) |
print( "ha".repeatString(5) ) |
||
print( "he".repeatString2(5) )</ |
print( "he".repeatString2(5) )</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,131: | Line 2,799: | ||
To repeat a single character: |
To repeat a single character: |
||
< |
<syntaxhighlight lang="swift">String(count:5, repeatedValue:"*" as Character) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note that using the String version on a string of 1 Character, or the repeat single Character version is timewise close to the same. No point in using the Character version for efficiency (tested with repeating up to 100 000 times). |
Note that using the String version on a string of 1 Character, or the repeat single Character version is timewise close to the same. No point in using the Character version for efficiency (tested with repeating up to 100 000 times). |
||
Line 2,139: | Line 2,807: | ||
The following version is an enhanced version of the [http://rosettacode.org/mw/index.php?title=Repeat_a_string#Recursive_version recursive ActionScript], where we're using bit operation along with iterative doubling of the string to get to the correctly repeated version of the text in the most effective manner without recursion. When benchmarked against the plain iterative version in previous section, this version is marginally better, but only my a very small percentage. The critical factor for making the repeat function effective when using larger strings (1000 characters) and multiple repeats (1000 repeats :-) ) was to to exchange the '+=' with 'String.extend' method. |
The following version is an enhanced version of the [http://rosettacode.org/mw/index.php?title=Repeat_a_string#Recursive_version recursive ActionScript], where we're using bit operation along with iterative doubling of the string to get to the correctly repeated version of the text in the most effective manner without recursion. When benchmarked against the plain iterative version in previous section, this version is marginally better, but only my a very small percentage. The critical factor for making the repeat function effective when using larger strings (1000 characters) and multiple repeats (1000 repeats :-) ) was to to exchange the '+=' with 'String.extend' method. |
||
< |
<syntaxhighlight lang="swift">extension String { |
||
func repeatBiterative(count: Int) -> String { |
func repeatBiterative(count: Int) -> String { |
||
var reduceCount = count |
var reduceCount = count |
||
Line 2,157: | Line 2,825: | ||
} |
} |
||
"He".repeatBiterative(5)</ |
"He".repeatBiterative(5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,164: | Line 2,832: | ||
=={{header|Tailspin}}== |
=={{header|Tailspin}}== |
||
< |
<syntaxhighlight lang="tailspin"> |
||
'$:1..5 -> 'ha';' -> !OUT::write |
'$:1..5 -> 'ha';' -> !OUT::write |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
< |
<syntaxhighlight lang="tcl">string repeat "ha" 5 ;# => hahahahaha</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
=={{header|TorqueScript}}== |
||
--[[User:Eepos|Eepos]] |
--[[User:Eepos|Eepos]] |
||
< |
<syntaxhighlight lang="torquescript">function strRep(%str,%int) |
||
{ |
{ |
||
for(%i = 0; %i < %int; %i++) |
for(%i = 0; %i < %int; %i++) |
||
Line 2,183: | Line 2,851: | ||
return %rstr; |
return %rstr; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tosh}}== |
=={{header|Tosh}}== |
||
< |
<syntaxhighlight lang="tosh">when flag clicked |
||
set String to "meow" |
set String to "meow" |
||
set Count to 4 |
set Count to 4 |
||
Line 2,193: | Line 2,861: | ||
set Repeated to (join (Repeated) (String)) |
set Repeated to (join (Repeated) (String)) |
||
end |
end |
||
stop this script</ |
stop this script</syntaxhighlight> |
||
=={{header|Transact-SQL}}== |
=={{header|Transact-SQL}}== |
||
< |
<syntaxhighlight lang="tsql">select REPLICATE( 'ha', 5 )</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
repeatstring=REPEAT ("ha",5) |
repeatstring=REPEAT ("ha",5) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
Line 2,209: | Line 2,877: | ||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
{{works with|zsh}} |
{{works with|zsh}} |
||
< |
<syntaxhighlight lang="bash">printf "ha"%.0s {1..5}</syntaxhighlight> |
||
With ksh93 and zsh, the count can vary. |
With ksh93 and zsh, the count can vary. |
||
Line 2,215: | Line 2,883: | ||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
{{works with|zsh}} |
{{works with|zsh}} |
||
< |
<syntaxhighlight lang="bash">i=5 |
||
printf "ha"%.0s {1..$i}</ |
printf "ha"%.0s {1..$i}</syntaxhighlight> |
||
With bash, <code>{1..$i}</code> fails, because brace expansion happens before variable substitution. The fix uses <code>eval</code>. |
With bash, <code>{1..$i}</code> fails, because brace expansion happens before variable substitution. The fix uses <code>eval</code>. |
||
Line 2,223: | Line 2,891: | ||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
{{works with|zsh}} |
{{works with|zsh}} |
||
< |
<syntaxhighlight lang="bash">i=5 |
||
eval "printf 'ha'%.0s {1..$i}"</ |
eval "printf 'ha'%.0s {1..$i}"</syntaxhighlight> |
||
For the general case, one must escape any % or \ characters in the string, because <code>printf</code> would interpret those characters. |
For the general case, one must escape any % or \ characters in the string, because <code>printf</code> would interpret those characters. |
||
Line 2,231: | Line 2,899: | ||
{{works with|ksh93}} |
{{works with|ksh93}} |
||
{{works with|zsh}} |
{{works with|zsh}} |
||
< |
<syntaxhighlight lang="bash">reprint() { |
||
typeset e="$(sed -e 's,%,%%,g' -e 's,\\,\\\\,g' <<<"$1")" |
typeset e="$(sed -e 's,%,%%,g' -e 's,\\,\\\\,g' <<<"$1")" |
||
eval 'printf "$e"%.0s '"{1..$2}" |
eval 'printf "$e"%.0s '"{1..$2}" |
||
} |
} |
||
reprint '% ha \' 5</ |
reprint '% ha \' 5</syntaxhighlight> |
||
=== Using repeat === |
=== Using repeat === |
||
Line 2,241: | Line 2,909: | ||
{{works with|csh}} |
{{works with|csh}} |
||
< |
<syntaxhighlight lang="bash"> |
||
len=12; str='=' |
len=12; str='=' |
||
repeat $len printf "$str" |
repeat $len printf "$str" |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using head -c=== |
===Using head -c=== |
||
Line 2,251: | Line 2,919: | ||
{{works with|Bourne Shell}} |
{{works with|Bourne Shell}} |
||
< |
<syntaxhighlight lang="sh">width=72; char='=' |
||
head -c ${width} < /dev/zero | tr '\0' "$char"</ |
head -c ${width} < /dev/zero | tr '\0' "$char"</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
< |
<syntaxhighlight lang="ursala">#import nat |
||
repeat = ^|DlSL/~& iota |
repeat = ^|DlSL/~& iota |
||
Line 2,261: | Line 2,929: | ||
#cast %s |
#cast %s |
||
example = repeat('ha',5)</ |
example = repeat('ha',5)</syntaxhighlight> |
||
output: |
output: |
||
<pre>'hahahahaha'</pre> |
<pre>'hahahahaha'</pre> |
||
Line 2,267: | Line 2,935: | ||
=={{header|Vala}}== |
=={{header|Vala}}== |
||
Repeat a string 5 times: |
Repeat a string 5 times: |
||
< |
<syntaxhighlight lang="vala"> |
||
string s = "ha"; |
string s = "ha"; |
||
string copy = ""; |
string copy = ""; |
||
for (int x = 0; x < 5; x++) |
for (int x = 0; x < 5; x++) |
||
copy += s; |
copy += s; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Fill a string with a char N times: |
Fill a string with a char N times: |
||
< |
<syntaxhighlight lang="vala"> |
||
string s = string.nfill(5, 'c'); |
string s = string.nfill(5, 'c'); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
<br>'''Repeat a string'''<br> |
<br>'''Repeat a string'''<br> |
||
< |
<syntaxhighlight lang="vba">Public Function RepeatStr(aString As String, aNumber As Integer) As String |
||
Dim bString As String, i As Integer |
Dim bString As String, i As Integer |
||
bString = "" |
bString = "" |
||
Line 2,290: | Line 2,958: | ||
End Function |
End Function |
||
Debug.Print RepeatStr("ha", 5)</ |
Debug.Print RepeatStr("ha", 5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,297: | Line 2,965: | ||
''Note:'' "String(5, "ha") in VBA produces "hhhhh" (only the first character is repeated)! |
''Note:'' "String(5, "ha") in VBA produces "hhhhh" (only the first character is repeated)! |
||
<p>An alternative method: |
<p>An alternative method: |
||
< |
<syntaxhighlight lang="vba">Public Function RepeatString(stText As String, iQty As Integer) As String |
||
RepeatString = Replace(String(iQty, "x"), "x", stText) |
RepeatString = Replace(String(iQty, "x"), "x", stText) |
||
End Function</ |
End Function</syntaxhighlight> |
||
<br>'''Repeat a character'''<br> |
<br>'''Repeat a character'''<br> |
||
< |
<syntaxhighlight lang="vba">Debug.Print String(5, "x")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>xxxxx</pre> |
<pre>xxxxx</pre> |
||
Line 2,307: | Line 2,975: | ||
=={{header|VBScript}}== |
=={{header|VBScript}}== |
||
{{works with|Windows Script Host|*}} |
{{works with|Windows Script Host|*}} |
||
<syntaxhighlight lang="vbscript"> |
|||
<lang VBScript> |
|||
' VBScript has a String() function that can repeat a character a given number of times |
' VBScript has a String() function that can repeat a character a given number of times |
||
' but this only works with single characters (or the 1st char of a string): |
' but this only works with single characters (or the 1st char of a string): |
||
Line 2,315: | Line 2,983: | ||
WScript.Echo Replace(Space(10), " ", "Ha") |
WScript.Echo Replace(Space(10), " ", "Ha") |
||
WScript.Echo Replace(String(10, "X"), "X", "Ha") |
WScript.Echo Replace(String(10, "X"), "X", "Ha") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |
||
< |
<syntaxhighlight lang="vedit">Ins_Text("ha", COUNT, 5) </syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
{{works with|Visual Basic|VB6 Standard}} |
{{works with|Visual Basic|VB6 Standard}} |
||
<br>'''Repeat a string'''<br> |
<br>'''Repeat a string'''<br> |
||
< |
<syntaxhighlight lang="vb">Public Function StrRepeat(s As String, n As Integer) As String |
||
Dim r As String, i As Integer |
Dim r As String, i As Integer |
||
r = "" |
r = "" |
||
Line 2,332: | Line 3,000: | ||
End Function |
End Function |
||
Debug.Print StrRepeat("ha", 5)</ |
Debug.Print StrRepeat("ha", 5)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
An alternative method: |
An alternative method: |
||
< |
<syntaxhighlight lang="vb">Public Function StrRepeat(sText As String, n As Integer) As String |
||
StrRepeat = Replace(String(n, "*"), "*", sText) |
StrRepeat = Replace(String(n, "*"), "*", sText) |
||
End Function</ |
End Function</syntaxhighlight> |
||
<br>'''Repeat a character'''<br> |
<br>'''Repeat a character'''<br> |
||
< |
<syntaxhighlight lang="vba">Debug.Print String(5, "x")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>xxxxx</pre> |
<pre>xxxxx</pre> |
||
Line 2,348: | Line 3,016: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
<br>'''Repeat a string'''<br> |
<br>'''Repeat a string'''<br> |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Debug.Print(Replace(Space(5), " ", "Ha")) |
Debug.Print(Replace(Space(5), " ", "Ha")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,357: | Line 3,025: | ||
<br>'''Repeat a character'''<br> |
<br>'''Repeat a character'''<br> |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Debug.Print(StrDup(5, "x")) |
Debug.Print(StrDup(5, "x")) |
||
Debug.Print("".PadRight(5, "x")) |
Debug.Print("".PadRight(5, "x")) |
||
Debug.Print("".PadLeft(5, "x")) |
Debug.Print("".PadLeft(5, "x")) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,371: | Line 3,039: | ||
=={{header|Visual FoxPro}}== |
=={{header|Visual FoxPro}}== |
||
Use the built in function REPLICATE(string, number): |
Use the built in function REPLICATE(string, number): |
||
< |
<syntaxhighlight lang="vfp">? REPLICATE("HO", 3)</syntaxhighlight> |
||
produces |
produces |
||
<pre>HOHOHO</pre> |
<pre>HOHOHO</pre> |
||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="go">// Repeat a string, in V |
|||
// Tectonics: v run repeat-a-string.v |
|||
module main |
|||
import strings |
|||
// starts here |
|||
pub fn main() { |
|||
// A strings module function to repeat strings |
|||
println(strings.repeat_string("ha", 5)) |
|||
// Another strings module function to repeat a byte |
|||
// This indexes the string to get the first byte of the rune array |
|||
println(strings.repeat("*"[0], 5)) |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ v run rosetta/repeat-a-string.v |
|||
hahahahaha |
|||
*****</pre> |
|||
=={{header|VBScript}}== |
|||
<syntaxhighlight lang="vb"> |
|||
replace(string(5,"@"),"@","hello") |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<small> |
|||
<pre> |
|||
hellohellohellohellohello |
|||
</pre> |
|||
</small> |
|||
=={{header|Wart}}== |
=={{header|Wart}}== |
||
< |
<syntaxhighlight lang="wart">def (s * n) :case (string? s) |
||
with outstring |
with outstring |
||
repeat n |
repeat n |
||
Line 2,383: | Line 3,083: | ||
("ha" * 5) |
("ha" * 5) |
||
=> "hahahahaha"</ |
=> "hahahahaha"</syntaxhighlight> |
||
=={{header|Wortel}}== |
=={{header|Wortel}}== |
||
< |
<syntaxhighlight lang="wortel">@join "" @rep 5 "ha" ; returns "hahahahaha"</syntaxhighlight> |
||
As a function: |
As a function: |
||
< |
<syntaxhighlight lang="wortel">^(\@join "" @rep)</syntaxhighlight> |
||
=={{header|Wren}}== |
|||
<syntaxhighlight lang="wren">System.print("ha" * 5)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hahahahaha |
|||
</pre> |
|||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">cod T=12; int I; for I gets 1,5 do T(0,"ha")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>hahahahaha</pre> |
<pre>hahahahaha</pre> |
||
=={{header|Yorick}}== |
=={{header|Yorick}}== |
||
< |
<syntaxhighlight lang="yorick">array("ha", 5)(sum)</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
|||
<syntaxhighlight lang="z80">PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints the ascii code in the accumulator to the screen. |
|||
org &8000 |
|||
ld b,5 ; repeat 5 times |
|||
loop: |
|||
call PrintImmediate |
|||
byte "ha",0 |
|||
djnz loop |
|||
ret ; return to basic |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
PrintImmediate: |
|||
pop hl ; get the return address into HL, it's the start of the embedded string. |
|||
call PrintString |
|||
; inc hl ; if your strings are null-terminated you can omit this, since a 0 equals the "NOP" instruction |
|||
jp (hl) ; acts as a ret, returning execution to the instruction just after the embedded string. |
|||
PrintString: |
|||
ld a,(hl) ; read in a character from the string |
|||
or a ; if your strings are null-terminated you can use this as a shortcut, otherwise use the compare instruction |
|||
ret z ; exit once the terminator is reached. |
|||
call PrintChar ; BIOS call, all regs are preserved. |
|||
inc hl ; next char |
|||
jr PrintString ; back to start.</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
hahahahaha |
|||
</pre> |
|||
=={{header|zig}}== |
=={{header|zig}}== |
||
At compile-time: |
At compile-time: |
||
< |
<syntaxhighlight lang="zig">const laugh = "ha" ** 5;</syntaxhighlight> |
||
Note that to achieve this at run-time in zig (in order to avoid hidden overflows) you must manage the memory yourself. |
Note that to achieve this at run-time in zig (in order to avoid hidden overflows) you must manage the memory yourself. |
||
< |
<syntaxhighlight lang="zig">const std = @import("std"); |
||
const warn = std.debug.warn; |
const warn = std.debug.warn; |
||
Line 2,422: | Line 3,162: | ||
const ex = try repeat("ha", 5, allocator); |
const ex = try repeat("ha", 5, allocator); |
||
defer allocator.free(ex); |
defer allocator.free(ex); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
Same as [[#Ruby|Ruby]] |
Same as [[#Ruby|Ruby]] |
||
< |
<syntaxhighlight lang="zkl">"ha" * 5 # --> "hahahahaha"</syntaxhighlight> |
||
Revision as of 22:04, 16 June 2024
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) => "*****").
- Metrics
- Counting
- Word frequency
- Letter frequency
- Jewels and stones
- I before E except after C
- Bioinformatics/base count
- Count occurrences of a substring
- Count how many vowels and consonants occur in a string
- Remove/replace
- XXXX redacted
- Conjugate a Latin verb
- Remove vowels from a string
- String interpolation (included)
- Strip block comments
- Strip comments from a string
- Strip a set of characters from a string
- Strip whitespace from a string -- top and tail
- Strip control codes and extended characters from a string
- Anagrams/Derangements/shuffling
- Word wheel
- ABC problem
- Sattolo cycle
- Knuth shuffle
- Ordered words
- Superpermutation minimisation
- Textonyms (using a phone text pad)
- Anagrams
- Anagrams/Deranged anagrams
- Permutations/Derangements
- Find/Search/Determine
- ABC words
- Odd words
- Word ladder
- Semordnilap
- Word search
- Wordiff (game)
- String matching
- Tea cup rim text
- Alternade words
- Changeable words
- State name puzzle
- String comparison
- Unique characters
- Unique characters in each string
- Extract file extension
- Levenshtein distance
- Palindrome detection
- Common list elements
- Longest common suffix
- Longest common prefix
- Compare a list of strings
- Longest common substring
- Find common directory path
- Words from neighbour ones
- Change e letters to i in words
- Non-continuous subsequences
- Longest common subsequence
- Longest palindromic substrings
- Longest increasing subsequence
- Words containing "the" substring
- Sum of the digits of n is substring of n
- Determine if a string is numeric
- Determine if a string is collapsible
- Determine if a string is squeezable
- Determine if a string has all unique characters
- Determine if a string has all the same characters
- Longest substrings without repeating characters
- Find words which contains all the vowels
- Find words which contain the most consonants
- Find words which contains more than 3 vowels
- Find words whose first and last three letters are equal
- Find words with alternating vowels and consonants
- Formatting
- Substring
- Rep-string
- Word wrap
- String case
- Align columns
- Literals/String
- Repeat a string
- Brace expansion
- Brace expansion using ranges
- Reverse a string
- Phrase reversals
- Comma quibbling
- Special characters
- String concatenation
- Substring/Top and tail
- Commatizing numbers
- Reverse words in a string
- Suffixation of decimal numbers
- Long literals, with continuations
- Numerical and alphabetical suffixes
- Abbreviations, easy
- Abbreviations, simple
- Abbreviations, automatic
- Song lyrics/poems/Mad Libs/phrases
- Mad Libs
- Magic 8-ball
- 99 bottles of beer
- The Name Game (a song)
- The Old lady swallowed a fly
- The Twelve Days of Christmas
- Tokenize
- Text between
- Tokenize a string
- Word break problem
- Tokenize a string with escaping
- Split a character string based on change of character
- Sequences
11l
print(‘ha’ * 5)
- Output:
hahahahaha
360 Assembly
* Repeat a string - 19/04/2020
REPEATS CSECT
USING REPEATS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
XPRNT C24,24 print c24
LA R1,PARMLST pg=repeat(cx,ii) - repeat('abc ',6)
BAL R14,REPEAT call repeat
XPRNT PG,L'PG print pg
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling save
REPEAT CNOP 0,4 procedure repeat(b,a,i)
STM R2,R8,REPEATSA save registers
L R2,0(R1) @b=%r1
L R3,4(R1) @a=%(r1+4)
L R4,8(R1) @i=%(r1+8)
LR R5,R3 length(a) before a
SH R5,=H'2' @lengh(a)
LH R6,0(R5) l=length(a)
LR R7,R6 l
BCTR R7,0 l-1
L R8,0(R4) i=%r4
LTR R8,R8 if i<=0
BNP RET then return
LOOP EX R7,MVCX move a to b len R6
AR R2,R6 @b+=l
BCT R8,LOOP loop i times
RET LM R2,R8,REPEATSA restore registers
BR R14 return
PARMLST DC A(PG,CX,II) parmlist
REPEATSA DS 7F local savearea
MVCX MVC 0(0,R2),0(R3) move @ R3 to @ R2
C24 DC 6C'xyz ' constant repeat - repeat('xyz ',6)
LCX DC AL2(L'CX) lengh(cc)
CX DC CL4'abc ' cx
II DC F'6' ii
PG DC CL80' ' pg
REGEQU
END REPEATS
- Output:
xyz xyz xyz xyz xyz xyz abc abc abc abc abc abc
4DOS Batch
gosub repeat ha 5
echo %@repeat[*,5]
quit
:Repeat [String Times]
do %Times%
echos %String%
enddo
echo.
return
Output shows:
hahahahaha *****
6502 Assembly
CHROUT equ $FFD2 ;KERNAL call, prints the accumulator to the screen as an ascii value.
org $0801
db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00
lda #>TestStr
sta $11
lda #<TestStr
sta $10
ldx #5 ;number of times to repeat
loop:
jsr PrintString
dex
bne loop
RTS ;RETURN TO BASIC
PrintString:
ldy #0
loop_PrintString:
lda ($10),y ;this doesn't actually increment the pointer itself, so we don't need to back it up.
beq donePrinting
jsr CHROUT
iny
jmp loop_PrintString
donePrinting:
rts
TestStr:
db "HA",0
- Output:
READY. LOAD"*",8,1: SEARCHING FOR * LOADING READY. RUN HAHAHAHAHA READY.
68000 Assembly
Easiest way to do this is with a loop.
MOVE.W #5-1,D1
RepString:
LEA A3, MyString
MOVE.L A3,-(SP) ;PUSH A3
JSR PrintString ;unimplemented hardware-dependent printing routine, assumed to not clobber D1
MOVE.L (SP)+,A3 ;POP A3
DBRA D1,RepString
RTS ;return to basic or whatever
MyString:
DC.B "ha",0
even
8080 Assembly
org 100h
jmp demo
; Repeat the string at DE into HL, B times
repeat: mvi c,'$' ; string terminator
xra a ; repeat 0x?
ora b
mov m,c ; then empty string
rz
rpt1: push d ; save begin of string to repeat
chcpy: ldax d ; copy character from input to output
mov m,a
inx d ; advance pointers
inx h
cmp c ; end of string?
jnz chcpy
pop d ; restore begin of string to repeat
dcx h ; move back past terminator in copy
dcr b ; done yet?
jnz rpt1 ; if not add another copy
ret
demo: lxi d,ha ; get string to repeat
lxi h,buf ; place to store result
mvi b,5 ; repeat 5 times
call repeat
lxi d,buf ; print result using CP/M call
mvi c,9
jmp 5
ha: db 'ha$' ; string to repeat
buf: ds 32 ; place to store repeated string
- Output:
hahahahaha
8th
"ha" 5 s:*
. cr
Output shows:
hahahahaha
ABAP
This works for ABAP Version 7.40 and above
report z_repeat_string.
write repeat( val = `ha` occ = 5 ).
- Output:
hahahahaha
Action!
Proc Main()
byte REPEAT
REPEAT=5
Do
Print("ha")
REPEAT==-1
Until REPEAT=0
Do
Return
- Output:
hahahahaha
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().
Iterative version
function repeatString(string:String, numTimes:uint):String
{
var output:String = "";
for(var i:uint = 0; i < numTimes; i++)
output += string;
return output;
}
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;
}
Flex
import mx.utils.StringUtil;
trace(StringUtil.repeat("ha", 5));
Sample Output:
hahahahaha
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
Aime
call_n(5, o_text, "ha");
ALGOL 68
print (5 * "ha")
Amazing Hopper
#!/usr/bin/hopper
#include <hopper.h>
main:
{"ha"}replyby(5), println
{"ha",5}replicate, println
{0}return
hahahahaha hahahahaha
APL
Fill up a string of length 10 with 'ha':
10⍴'ha'
hahahahaha
Alternatively, define a function:
REPEAT←{(⍺×⍴⍵)⍴⍵}
5 REPEAT 'ha'
hahahahaha
AppleScript
set str to "ha"
set final_string to ""
repeat 5 times
set final_string to final_string & str
end repeat
For larger numbers of repetitions, however, it proves significantly faster to progressively double a copy of the original string (concatenating it with itself). Intermediate stages of doubling are appended to an accumulator wherever required for binary composition of the target number.
See the technique of 'Egyptian Multiplication' described in the Rhind Mathematical Papyrus at the British Museum.
replicate(5000, "ha")
-- Repetition by 'Egyptian multiplication' -
-- progressively doubling a list, appending
-- stages of doubling to an accumulator where needed for
-- binary assembly of a target length.
-- replicate :: Int -> String -> String
on replicate(n, s)
set out to ""
if n < 1 then return out
set dbl to s
repeat while (n > 1)
if (n mod 2) > 0 then set out to out & dbl
set n to (n div 2)
set dbl to (dbl & dbl)
end repeat
return out & dbl
end replicate
Applesoft BASIC
FOR I = 1 TO 5 : S$ = S$ + "HA" : NEXT
? "X" SPC(20) "X"
Output:
X X
Arturo
print repeat "ha" 5
- Output:
hahahahaha
AutoHotkey
MsgBox % Repeat("ha",5)
Repeat(String,Times)
{
Loop, %Times%
Output .= String
Return Output
}
AutoIt
#include <String.au3>
ConsoleWrite(_StringRepeat("ha", 5) & @CRLF)
AWK
function repeat( str, n, rep, i )
{
for( ; i<n; i++ )
rep = rep str
return rep
}
BEGIN {
print repeat( "ha", 5 )
}
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
BaCon
To repeat a string:
DOTIMES 5
s$ = s$ & "ha"
DONE
PRINT s$
- Output:
hahahahaha
To repeat one single character:
PRINT FILL$(5, ASC("x"))
- Output:
xxxxx
BASIC
BASIC256
function StringRepeat$ (s$, n)
cad$ = ""
for i = 1 to n
cad$ += s$
next i
return cad$
end function
print StringRepeat$("rosetta", 1)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
end
Chipmunk Basic
100 cls
110 print stringrepeat$("rosetta",1)
120 print stringrepeat$("ha",5)
130 print stringrepeat$("*",5)
140 end
150 function stringrepeat$(s$,n)
160 cad$ = ""
170 for i = 1 to n
180 cad$ = cad$+s$
190 next i
200 stringrepeat$ = cad$
210 end function
GW-BASIC
100 CLS : rem 100 HOME for Applesoft BASIC
110 S$ = "rosetta" : N = 1
120 GOSUB 210
130 PRINT CAD$
140 S$ = "ha" : N = 5
150 GOSUB 210
160 PRINT CAD$
170 S$ = "*" : N = 5
180 GOSUB 210
190 PRINT CAD$
200 END
210 REM FUNCTION STRINGREPEAT$(S$,N)
220 CAD$ = ""
230 FOR I = 1 TO N
240 CAD$ = CAD$+S$
250 NEXT I
260 RETURN
Minimal BASIC
100 REM Repeat a string
110 LET S$ = "rosetta"
120 LET N = 1
130 GOSUB 210
140 LET S$ = "ha"
150 LET N = 5
160 GOSUB 210
170 LET S$ = "*"
180 LET N = 5
190 GOSUB 210
200 STOP
210 REM FUNCTION StringRepeat$(S$,N)
220 FOR I = 1 TO N
230 PRINT S$;
240 NEXT I
250 PRINT
260 RETURN
270 END
MSX Basic
The GW-BASIC solution works without any changes.
QBasic
FUNCTION StringRepeat$ (s$, n)
cad$ = ""
FOR i = 1 TO n
cad$ = cad$ + s$
NEXT i
StringRepeat$ = cad$
END FUNCTION
PRINT StringRepeat$("rosetta", 1)
PRINT StringRepeat$("ha", 5)
PRINT StringRepeat$("*", 5)
END
Quite BASIC
100 CLS
110 LET S$ = "rosetta"
115 LET N = 1
120 GOSUB 210
130 PRINT C$
140 LET S$ = "ha"
145 LET N = 5
150 GOSUB 210
160 PRINT C$
170 LET S$ = "*"
175 LET N = 5
180 GOSUB 210
190 PRINT C$
200 END
210 REM FUNCTION STRINGREPEAT$(S$,N)
220 LET C$ = ""
230 FOR I = 1 TO N
240 LET C$ = C$ + S$
250 NEXT I
260 RETURN
True BASIC
FUNCTION StringRepeat$ (s$, n)
LET cad$ = ""
FOR i = 1 TO n
LET cad$ = cad$ & s$
NEXT i
LET StringRepeat$ = cad$
END FUNCTION
PRINT StringRepeat$("rosetta", 1)
PRINT StringRepeat$("ha", 5)
PRINT StringRepeat$("*", 5)
END
XBasic
PROGRAM "Repeat a string"
VERSION "0.0000"
DECLARE FUNCTION Entry ()
DECLARE FUNCTION StringRepeat$ (s$, n)
FUNCTION Entry ()
PRINT StringRepeat$ ("rosetta", 1)
PRINT StringRepeat$ ("ha", 5)
PRINT StringRepeat$ ("*", 5)
END FUNCTION
FUNCTION StringRepeat$ (s$, n)
cad$ = ""
FOR i = 1 TO n
cad$ = cad$ + s$
NEXT i
RETURN cad$
END FUNCTION
END PROGRAM
Yabasic
sub StringRepeat$ (s$, n)
cad$ = ""
for i = 1 to n
cad$ = cad$ + s$
next i
return cad$
end sub
print StringRepeat$("rosetta", 1)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
end
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
BBC BASIC
PRINT STRING$(5, "ha")
beeswax
p <
p0~1<}~< d@<
_VT@1~>yg~9PKd@M'd;
Example:
julia> beeswax("repeat a string.bswx") sha i5 hahahahaha Program finished!
s
tells the user that the program expects a string as input.
i
tells the user that the program expects an integer as input.
Beef
String s = new String('X', 5);
s.Replace("X", "ha");
And for single character repeats
String s1 = scope .();
s1.PadLeft(5, '*');
Befunge
v> ">:#,_v
>29*+00p>~:"0"- #v_v $
v ^p0p00:-1g00< $ >
v p00&p0-1g00+4*65< >00g1-:00p#^_@
Input sample:
ha05
Input string has to be zero terminated and less than 18 characters.
Output sample:
hahahahaha
BQN
⥊
(reshape) can all by itself be used to repeat a string to a particular length. This function is just a wrapper around it to repeat n times.
Repeat ← ×⟜≠ ⥊ ⊢
•Show 5 Repeat "Hello"
"HelloHelloHelloHelloHello"
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
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
+++++ +++++ +++ . --- .
Brat
p "ha" * 5 #Prints "hahahahaha"
Burlesque
blsq ) 'h5?*
"hhhhh"
blsq ) "ha"5.*\[
"hahahahaha"
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.
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);
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 ;
}
recursive version
#include <string>
#include <iostream>
std::string repeat( const std::string &word, uint times ) {
return
times == 0 ? "" :
times == 1 ? word :
times == 2 ? word + word :
repeat(repeat(word, times / 2), 2) +
repeat(word, times % 2);
}
int main( ) {
std::cout << repeat( "Ha" , 5 ) << std::endl ;
return 0 ;
}
Ceylon
shared void repeatAString() {
print("ha".repeat(5));
}
Clipper
Also works with Harbour Project compiler Harbour 3.0.0 (Rev. 16951)
Replicate( "Ha", 5 )
Clojure
(apply str (repeat 5 "ha"))
COBOL
Virtually a one-liner.
IDENTIFICATION DIVISION.
PROGRAM-ID. REPEAT-PROGRAM.
DATA DIVISION.
WORKING-STORAGE SECTION.
77 HAHA PIC A(10).
PROCEDURE DIVISION.
MOVE ALL 'ha' TO HAHA.
DISPLAY HAHA.
STOP RUN.
- Output:
hahahahaha
ColdFusion
<cfset word = 'ha'>
<Cfset n = 5>
<Cfoutput>
<Cfloop from="1" to="#n#" index="i">#word#</Cfloop>
</Cfoutput>
Common Lisp
(defun repeat-string (n string)
(with-output-to-string (stream)
(loop repeat n do (write-string string stream))))
A version which allocates the result string in one step:
(defun repeat-string (n string
&aux
(len (length string))
(result (make-string (* n len)
:element-type (array-element-type string))))
(loop repeat n
for i from 0 by len
do (setf (subseq result i (+ i len)) string))
result)
For those who love one-liners, even at the expense of readability:
(defun repeat-string (n string)
(format nil "~V@{~a~:*~}" n string))
(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”.
Crystal
puts "ha" * 5
hahahahaha
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);
}
DCL
Not exactly what the task asks for but at least it is something;
$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" )
$ write sys$output f$fao( "!12*d" )
- Output:
$ @repeat_a_string_and_then_character hahahahaha dddddddddddd
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) );
Using recursion
function RepeatStr(const s: string; i: Cardinal): string;
begin
if i = 0 then
result := ''
else
result := s + RepeatStr(s, i-1)
end;
Built in RTL function:
StrUtils.DupeString
DWScript
Repeat a string
PrintLn( StringOfString('abc',5) );
Repeat a character
PrintLn( StringOfChar('a',5) );
Dyalect
String.Repeat("ha", 5)
Déjà Vu
!. concat( rep 5 "ha" )
- Output:
"hahahahaha"
E
"ha" * 5
EasyLang
func$ rep s$ n .
for i to n
r$ &= s$
.
return r$
.
print rep "ha" 5
ECL
After version 4.2.2
IMPORT STD; //Imports the Standard Library
STRING MyBaseString := 'abc';
RepeatedString := STD.Str.Repeat(MyBaseString,3);
RepeatedString; //returns 'abcabcabc'
Before version 4.2.2
RepeatString(STRING InStr, INTEGER Cnt) := FUNCTION
rec := {STRING Str};
ds := DATASET(Cnt,TRANSFORM(rec,SELF.Str := InStr));
res := ITERATE(ds,TRANSFORM(rec,SELF.Str := LEFT.Str + RIGHT.Str));
RETURN Res[Cnt].Str;
END;
RepeatString('ha',3);
RepeatString('Who',2);
Ecstasy
String funny = "ha" * 5;
String stars = '*' * 80;
Egison
(S.concat (take 5 (repeat1 "ha")))
Eiffel
repeat_string(a_string: STRING; times: INTEGER): STRING
require
times_positive: times > 0
do
Result := a_string.multiply(times)
end
Elena
ELENA 6.x :
import system'routines;
import extensions;
import extensions'text;
public program()
{
var s := new Range(0, 5).selectBy::(x => "ha").summarize(new StringWriter())
}
Elixir
String.duplicate("ha", 5)
Emacs Lisp
Going via a list to repeat the desired string:
(apply 'concat (make-list 5 "ha"))
A single character can be repeated with make-string
:
(make-string 5 ?x)
The cl-loop
macro can repeat and concatenate:
(require 'cl-lib)
(cl-loop repeat 5 concat "ha")
Erlang
repeat(X,N) ->
lists:flatten(lists:duplicate(N,X)).
This will duplicate a string or character N times to produce a new string.
ERRE
PROCEDURE REPEAT_STRING(S$,N%->REP$)
LOCAL I%
REP$=""
FOR I%=1 TO N% DO
REP$=REP$+S$
END FOR
END PROCEDURE
Note: If N% is less than 1, the result is the empty string "".If S$ is a one-character string
you can use the predefined function STRING$
as REP$=STRING$(S$,N%)
.
Euphoria
A simple loop will do:
sequence s = ""
for i = 1 to 5 do s &= "ha" end for
puts(1,s)
hahahahaha
For repeating a single character:
sequence s = repeat('*',5)
*****
For repeating a string or sequence of numbers:
include std/console.e -- for display
include std/sequence.e -- for repeat_pattern
sequence s = repeat_pattern("ha",5)
sequence n = repeat_pattern({1,2,3},5)
display(s)
display(n)
hahahahaha
{1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}
But wait, here's another way:
include std/console.e -- for display
include std/sequence.e -- for flatten
sequence s = flatten(repeat("ha",5))
display(s)
note: repeat creates a sequence of ha's as shown below; flatten concatenates them.
{
"ha",
"ha",
"ha",
"ha",
"ha"
}
Explore
The Scratch solution, which requires making variables named "String", "Count", and "Repeated" first, works, unmodified:
https://i.ibb.co/yX3ybt7/Repeat-a-string-in-Explore-using-the-Scratch-solution.png
This example uses a special block located in the Strings category, and also outputs the results of the repeating of the string to a "say" block:
https://i.ibb.co/71x9rwn/Repeat-a-string-in-Explore-using-a-special-block.png
F#
> String.replicate 5 "ha";;
val it : string = "hahahahaha"
Or
> String.Concat( Array.create 5 "ha" );;
val it : string = "hahahahaha"
Factor
: repeat-string ( str n -- str' ) swap <repetition> concat ;
"ha" 5 repeat-string print
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 \ **********
Fortran
program test_repeat
write (*, '(a)') repeat ('ha', 5)
end program test_repeat
Output:
hahahahaha
Free Pascal
strUtils.dupeString('ha', 5)
Repetition of a single character:
stringOfChar('*', 5)
If the repeated character happens to be the space character:
space(5)
FreeBASIC
' FB 1.05.0 Win64
' A character is essentially a string of length 1 in FB though there is a built-in function, String,
' which creates a string by repeating a character a given number of times.
' To avoid repeated concatenation (a slow operation) when the string to be repeated has a length
' greater than one, we instead create a buffer of the required size and then fill that.
Function repeat(s As String, n As Integer) As String
If n < 1 Then Return ""
If n = 1 Then Return s
Var size = Len(s)
If size = 0 Then Return s ' empty string
If size = 1 Then Return String(n, s[0]) ' repeated single character
Var buffer = Space(size * n) 'create buffer for size > 1
For i As Integer = 0 To n - 1
For j As Integer = 0 To size - 1
buffer[i * size + j] = s[j]
Next j
Next i
Return buffer
End Function
Print repeat("rosetta", 1)
Print repeat("ha", 5)
Print repeat("*", 5)
Print
Print "Press any key to quit program"
Sleep
- Output:
rosetta hahahahaha *****
Frink
println[repeat["ha", 5]]
FutureBasic
include "NSLog.incl"
CFStringRef repeatStr
repeatStr = @"Hello, World!\n"
NSLog( @"%@", fn StringByPaddingToLength( @"", 50 * len(repeatStr), repeatStr, 0 ) )
HandleEvents
- Output:
[50 line repetitions of "Hello, World!"]
Gambas
Click this link to run this code
Public Sub Main()
Print String$(5, "ha")
End
Output = hahahahaha
GAP
Concatenation(ListWithIdenticalEntries(10, "BOB "));
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "
Glee
'*' %% 5
'ha' => Str;
Str# => Len;
1..Len %% (Len * 5) => Idx;
Str [Idx] $;
'ha'=>S[1..(S#)%%(S# *5)]
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
Groovy
println 'ha' * 5
Harbour
? Replicate( "Ha", 5 )
Haskell
For a string of finite length:
concat $ replicate 5 "ha"
Or with list-monad (a bit obscure):
[1..5] >> "ha"
Or with Control.Applicative:
[1..5] *> "ha"
For an infinitely long string:
cycle "ha"
To repeat a single character:
replicate 5 '*'
Or, unpacking the mechanism of replicate a little, and using a mappend-based rep in lieu of the cons-based repeat, so that we can skip a subsequent concat:
repString :: String -> Int -> String
repString s n =
let rep x = xs
where
xs = mappend x xs
in take (n * length s) (rep s)
main :: IO ()
main = print $ repString "ha" 5
- Output:
"hahahahaha"
As the number of repetitions grows, however, it may become more efficient to repeat by progressive duplication (mappend to self), mappending to an accumulator only where required for binary composition of the target length. (i.e. Rhind Papyrus 'Egyptian' or 'Ethiopian' multiplication):
import Data.Tuple (swap)
import Data.List (unfoldr)
import Control.Monad (join)
-- BY RHIND PAPYRUS 'EGYPTIAN' OR 'ETHIOPIAN' MULTIPLICATION ------------------
repString :: Int -> String -> String
repString n s =
foldr
(\(d, x) a ->
if d > 0 -- Is this power of 2 needed for the binary recomposition ?
then mappend a x
else a)
mempty $
zip
(unfoldr
(\h ->
if h > 0
then Just $ swap (quotRem h 2) -- Binary decomposition of n
else Nothing)
n)
(iterate (join mappend) s) -- Iterative duplication ( mappend to self )
-- TEST -----------------------------------------------------------------------
main :: IO ()
main = print $ repString 500 "ha"
HicEst
CHARACTER out*20
EDIT(Text=out, Insert="ha", DO=5)
Icon and Unicon
The procedure repl is a supplied function in Icon and Unicon.
If it weren't, one way to write it is:
Idris
strRepeat : Nat -> String -> String
strRepeat Z s = ""
strRepeat (S n) s = s ++ strRepeat n s
chrRepeat : Nat -> Char -> String
chrRepeat Z c = ""
chrRepeat (S n) c = strCons c $ chrRepeat n c
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.
Insitux
(str* "ha" 5)
- Output:
hahahahaha
IS-BASIC
10 PRINT STRING$("ha",5)
100 DEF STRING$(S$,N)
105 LET ST$=""
110 FOR I=1 TO N
120 LET ST$=ST$&S$
130 NEXT
140 LET STRING$=ST$
150 END DEF
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. using boxing to treat the array as a whole
hahahahaha
Java
There are a few ways to achieve this in Java.
Starting with Java 11 you can use the String.repeat method.
"ha".repeat(5);
Which, if you view its implementation, is just using the Arrays.fill method.
String[] strings = new String[5];
Arrays.fill(strings, "ha");
StringBuilder repeated = new StringBuilder();
for (String string : strings)
repeated.append(string);
And if you look at the 'Arrays.fill' implementation, it's just a for-loop, which is likely the most idiomatic approach.
String string = "ha";
StringBuilder repeated = new StringBuilder();
int count = 5;
while (count-- > 0)
repeated.append(string);
Or
Before Java 11 there was no method or operator to do this in Java, so you had to do it yourself.
public static String repeat(String str, int times) {
StringBuilder sb = new StringBuilder(str.length() * times);
for (int i = 0; i < times; i++)
sb.append(str);
return sb.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.
JavaScript
Extending the String prototype
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 || 0)).join(this);
}
console.log("ha".repeat(5)); // hahahahaha
As of ES6, `repeat` is built in, so this can be written as:
console.log("ha".repeat(5)); // hahahahaha
Repetition by Egyptian multiplication
For larger numbers of repetitions, however, it proves significantly faster to progressively double a copy of the original string (concatenating it with itself). Intermediate stages of doubling are appended to an accumulator wherever required for binary composition of the target number.
See the technique of 'Egyptian Multiplication' described in the Rhind Mathematical Papyrus at the British Museum.
(() => {
'use strict';
// replicate :: Int -> String -> String
const replicate = (n, s) => {
let v = [s],
o = [];
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o + v;
n >>= 1;
v = v + v;
}
return o.concat(v);
};
return replicate(5000, "ha")
})();
Concat . replicate
Or, more generically, we could derive repeat as the composition of concat and replicate
(() => {
'use strict';
// repeat :: Int -> String -> String
const repeat = (n, s) =>
concat(replicate(n, s));
// GENERIC FUNCTIONS ------------------------------------------------------
// concat :: [[a]] -> [a] | [String] -> String
const concat = xs =>
xs.length > 0 ? (() => {
const unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
})() : [];
// replicate :: Int -> a -> [a]
const replicate = (n, x) =>
Array.from({
length: n
}, () => x);
// TEST -------------------------------------------------------------------
return repeat(5, 'ha');
})();
- Output:
hahahahaha
Joy
DEFINE repeat == "" rotate [concat] cons times.
"ha" 5 repeat.
jq
"a " * 3 # => "a a a "
Note that if the integer multiplicand is 0, then the result is the JSON value null.
Julia
@show "ha" ^ 5
# The ^ operator is really just call to the `repeat` function
@show repeat("ha", 5)
K
,/5#,"ha"
"hahahahaha"
5#"*"
"*****"
Kotlin
fun main(args: Array<String>) {
println("ha".repeat(5))
}
Or more fancy:
operator fun String.times(n: Int) = this.repeat(n)
fun main(args: Array<String>) = println("ha" * 5)
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.
By using built in functions:
Lambdatalk
{S.map {lambda {_} ha} {S.serie 1 10}}
-> ha ha ha ha ha ha ha ha ha ha
or
{S.replace \s
by
in {S.map {lambda {_} ha}
{S.serie 1 10}}}
-> hahahahahahahahahaha
or
{def repeat
{lambda {:w :n}
{if {< :n 0}
then
else :w{repeat :w {- :n 1}}}}}
-> repeat
{repeat ha 10}
-> hahahahahahahahahahaha
Lang
# Repeat text function
fn.println(fn.repeatText(5, ha))
# Output: hahahahaha
# Mul operator
fn.println(parser.op(ha * 5))
# Output: hahahahaha
# Mul operator function
fn.println(fn.mul(ha, 5))
# Output: hahahahaha
langur
"ha" * 5
Lasso
'ha'*5 // hahahahaha
loop(5) => {^ 'ha' ^} // hahahahaha
LFE
(string:copies '"ha" 5)
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
Lingo
- Take a string and repeat it some number of times.
on rep (str, n)
res = ""
repeat with i = 1 to n
put str after res
end repeat
return res
end
put rep("ha", 5)
-- "hahahahaha"
- If there is a simpler/more efficient way to repeat a single “character”...
put bytearray(5, chartonum("*")).readRawString(5)
-- "*****"
LiveCode
on mouseUp
put repeatString("ha", 5)
end mouseUp
function repeatString str n
repeat n times
put str after t
end repeat
return t
end repeatString
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 "||
Lua
function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end
Or use native string library function
string.rep(s,n)
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.
Mathematica /Wolfram Language
StringRepeat["ha", 5]
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)
Maxima
"$*"(s, n) := apply(sconcat, makelist(s, n))$
infix("$*")$
"abc" $* 5;
/* "abcabcabcabcabc" */
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 ).
min
"ha" 5 repeat print
- Output:
hahahahaha
MiniScript
str = "Lol"
print str * 5
- Output:
LolLolLolLolLol
Mirah
x = StringBuilder.new
5.times do
x.append "ha"
end
puts x # ==> "hahahahaha"
Monte
var s := "ha " * 5
traceln(s)
MontiLang
|ha| 5 * PRINT .
Or with a loop
FOR 5
|ha| OUT .
ENDFOR || PRINT .
Or ...
|ha| FOR 5 OUT ENDFOR . || PRINT .
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
Nanoquery
In Nanoquery, multiplying strings by an integer returns a new string with the original value repeated.
"ha" * 5
Neko
/* Repeat a string, in Neko */
var srep = function(s, n) {
var str = ""
while n > 0 {
str += s
n -= 1
}
return str
}
$print(srep("ha", 5), "\n")
- Output:
prompt$ nekoc srep.neko prompt$ neko srep hahahahaha
Nemerle
Any of the methods shown in the C# solution would also work for Nemerle, but they're all semantically awkward. This example uses an extension method to wrap one of the awkward techniques in order to clarify the semantics (which is also possible in C#, there's nothing really Nemerle specific here except the syntax).
using System;
using System.Console;
module StrRep
{
Repeat(this s : string, n : int) : string
{
String('x', n).Replace("x", s)
}
Main() : void
{
WriteLine("ha".Repeat(5));
WriteLine("*".Repeat(5));
WriteLine(String('*', 5)); // repeating single char
}
}
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, '.')
NewLISP
(dup "ha" 5)
Nim
import strutils
# Repeat a char.
echo repeat('a', 5) # -> "aaaaa".
# Repeat a string.
echo repeat("ha", 5) # -> "hahahahaha".
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;
}
}
}
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);
OCaml
Since Ocaml 4.02 strings are immutable, as is convenient for a functional language. Mutable strings are now implemented in the module Bytes.
let string_repeat s n =
let s = Bytes.of_string s in
let len = Bytes.length s in
let res = Bytes.create (n * len) in
for i = 0 to pred n do
Bytes.blit s 0 res (i * len) len
done;
(Bytes.to_string res)
;;
which gives the signature
val string_repeat : string -> int -> string = <fun>
testing in the toplevel:
# string_repeat "Hiuoa" 3 ;;
- : string = "HiuoaHiuoaHiuoa"
Alternately create an array initialized to s, and concat:
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 use:
String.make 5 '*'
Oforth
StringBuffer new "abcd" <<n(5)
OpenEdge/Progress
MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.
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
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}}
PARI/GP
Version #1. Based on recursion.
This solution is recursive and 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), "")
};
concat()
joins together a vector of strings, in this case a single string repeated.
repeat(s,n)=concat(vector(n,i, s));
This solution is recursive and slightly less bad than the others for large n.
repeat(s,n)={
if(n<4, return(concat(vector(n,i, s))));
if(n%2,
Str(repeat(Str(s,s),n\2),s)
,
repeat(Str(s,s),n\2)
);
}
Version #2. Simple loop based.
Basic set of string functions is very handy for presentation purposes. At the same time, it is true that PARI/GP is not an appropriate tool for the heavy text processing.
\\ Repeat a string str the specified number of times ntimes and return composed string.
\\ 3/3/2016 aev
srepeat(str,ntimes)={
my(srez=str,nt=ntimes-1);
if(ntimes<1||#str==0,return(""));
if(ntimes==1,return(str));
for(i=1,nt, srez=concat(srez,str));
return(srez);
}
{
\\ TESTS
print(" *** Testing srepeat:");
print("1.",srepeat("a",5));
print("2.",srepeat("ab",5));
print("3.",srepeat("c",1));
print("4.|",srepeat("d",0),"|");
print("5.|",srepeat("",5),"|");
print1("6."); for(i=1,10000000, srepeat("e",10));
}
- Output:
*** Testing srepeat: 1.aaaaa 2.ababababab 3.c 4.|| 5.|| 6. (16:00) gp > ## *** last result computed in 1min, 2,939 ms.
Pascal
See Delphi or Free Pascal, as standard Pascal does not know strings of unlimited length.
PascalABC.NET
##
Print('ha' * 5)
- Output:
hahahahaha
Perl
"ha" x 5
Phix
?repeat('*',5) ?join(repeat("ha",5),"")
- Output:
"*****" "hahahahaha"
Phixmonti
def rep /# s n -- s #/
"" swap
for drop
over chain
endfor
nip
enddef
"ha" 5 rep print
Same result (simple character):
65 5 rep
65 5 repeat
'A' 5 repeat
PHP
str_repeat("ha", 5)
PicoLisp
(pack (need 5 "ha"))
-> "hahahahaha"
or:
(pack (make (do 5 (link "ha"))))
-> "hahahahaha"
Pike
"ha"*5;
PL/I
/* To repeat a string a variable number of times: */
s = repeat('ha', 4);
/* or */
s = copy('ha', 5);
/* To repeat a single character a fixed number of times: */
s = (5)'h'; /* asigns 'hhhhh' to s. */
Plain English
To run:
Start up.
Put "ha" into a string.
Append the string to itself given 5.
Write the string on the console.
Fill another string with the asterisk byte given 5.
Write the other string on the console.
Wait for the escape key.
Shut down.
To append a string to itself given a number:
If the number is less than 1, exit.
Privatize the string.
Privatize the number.
Subtract 1 from the number.
Append the string to the original string given the number.
- Output:
hahahahaha *****
Plorth
"ha" 5 *
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
PowerBASIC
MSGBOX REPEAT$(5, "ha")
PowerShell
"ha" * 5 # ==> "hahahahaha"
Processing
void setup() {
String rep = repeat("ha", 5);
println(rep);
}
String repeat(String str, int times) {
// make an array of n chars,
// replace each char with str,
// and return as a new String
return new String(new char[times]).replace("\0", str);
}
Processing Python mode
def setup():
rep = repeat("ha", 5)
println(rep)
def repeat(s, times):
return s * times
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).
alternative using DCG strings
This tail-recursive DCG implemention is more efficient than anything using lists:append .
:- system:set_prolog_flag(double_quotes,chars) .
repeat(SOURCEz0,COUNT0,TARGETz)
:-
prolog:phrase(repeat(SOURCEz0,COUNT0),TARGETz)
.
%! repeat(SOURCEz0,COUNT0)//2
repeat(_SOURCEz0_,0)
-->
! ,
[]
.
repeat(SOURCEz0,COUNT0)
-->
SOURCEz0 ,
{ COUNT is COUNT0 - 1 } ,
repeat(SOURCEz0,COUNT)
.
- Output:
/* ?- repeat("ha",5,TARGETz) . TARGETz = [h, a, h, a, h, a, h, a, h, a]. ?- */
:- begin_tests(basic) . :- system:set_prolog_flag(double_quotes,chars) . test('1',[]) :- repeat("a",2,"aa") . test('2',[]) :- repeat("ha",2,"haha") . test('3',[]) :- repeat("ha",3,"hahaha") . test('4',[]) :- repeat("",3,"") . test('5',[]) :- repeat("ha",0,"") . test('6',[]) :- repeat("ha",1,"ha") . :- end_tests(basic) .
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"
>
You can define str_repeat using infinite lazy list (stream).
str_repeat n::int s::string = string $ take n $ cycle (s:[]);
PureBasic
Procedure.s RepeatString(count, text$=" ")
Protected i, ret$=""
For i = 1 To count
ret$ + text$
Next
ProcedureReturn ret$
EndProcedure
Debug RepeatString(5, "ha")
Python
"ha" * 5 # ==> "hahahahaha"
"Characters" are just strings of length one.
the other way also works:
5 * "ha" # ==> "hahahahaha"
Using a Function
def repeat(s, times):
return s * times
print(repeat("ha", 5))
- Output:
hahahahaha
Using Lambda
x = lambda a: a * 5
print(x("ha"))
- Output:
hahahahaha
Quackery
$ "ha" 5 of echo$
Output:
hahahahaha
R
strrep("ha", 5)
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 #\*) => "*****"
Raku
(formerly Perl 6)
print "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
.)
RapidQ
'For a single char
showmessage String$(10, "-")
'For strings with more than one char
function Repeat$(Expr as string, Count as integer) as string
dim x as integer
for x = 1 to Count
Result = Result + Expr
next
end function
showmessage Repeat$("ha", 5)
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
REBOL
head insert/dup "" "ha" 5
Red
>> str: "Add duplicates to string"
>> insert/dup str "ha" 3
== "hahahaAdd duplicates to string"
>> insert/dup tail str "ha" 3
== "hahahaAdd duplicates to stringhahaha"
ReScript
Js.log(Js.String2.repeat("ha", 5))
Retro
with strings'
: repeatString ( $n-$ )
1- [ dup ] dip [ over prepend ] times nip ;
"ha" 5 repeatString
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.
Ring
Copy("ha" , 5) # ==> "hahahahaha"
RPL
≪ "" 1 5 START "ha" + NEXT ≫ EVAL
- Output:
1: "hahahahaha"
Ruby
"ha" * 5 # ==> "hahahahaha"
Run BASIC
a$ = "ha "
for i = 1 to 5
a1$ = a1$ + a$
next i
a$ = a1$
print a$
Rust
std::iter::repeat("ha").take(5).collect::<String>(); // ==> "hahahahaha"
Since 1.16:
"ha".repeat(5); // ==> "hahahahaha"
Scala
"ha" * 5 // ==> "hahahahaha"
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 #\*)
Scratch
This example requires making variables named "String", "Count", and "Repeated" first.
sed
Number of ampersands indicates number of repetitions.
$ echo ha | sed 's/.*/&&&&&/'
hahahahaha
Seed7
$ include "seed7_05.s7i";
const proc: main is func
begin
writeln("ha" mult 5);
end func;
Output:
hahahahaha
SenseTalk
put "Ho!" repeated 3 times
put "Merry" repeated to length 12
Output:
Ho!Ho!Ho! MerryMerryMe
Sidef
'ha' * 5; # ==> 'hahahahaha'
Sinclair ZX81 BASIC
Works with 1k of RAM. This program defines a subroutine that expects to find a string and a number of times to repeat it; but all it then does is loop and concatenate, so making it a separate subroutine is arguably overkill.
10 LET S$="HA"
20 LET N=5
30 GOSUB 60
40 PRINT T$
50 STOP
60 LET T$=""
70 FOR I=1 TO N
80 LET T$=T$+S$
90 NEXT I
100 RETURN
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:$*
(String new:n) atAllPut:$*
SNOBOL4
output = dupl("ha",5)
end
Sparkling
spn:3> repeat("na", 8) .. " Batman!"
= nananananananana Batman!
SQL
select rpad('', 10, 'ha')
SQL PL
VALUES REPEAT('ha', 5);
VALUES RPAD('', 10, 'ha');
Output:
db2 -t db2 => VALUES REPEAT('ha', 5); 1 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- hahahahaha 1 record(s) selected. db2 => VALUES RPAD('', 10, 'ha'); 1 ---------- hahahahaha 1 record(s) selected.
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))
;
Stata
. scalar a="ha"
. scalar b=a*5
. display b
hahahahaha
Suneido
'ha'.Repeat(5) --> "hahahahaha"
'*'.Repeat(5) --> "*****"
Swift
The Builtin Way
print(String(repeating:"*", count: 5))
- Output:
*****
Functions
func * (left:String, right:Int) -> String {
return String(repeating:left, count:right)
}
print ("HA" * 5)
- Output:
HAHAHAHAHA
Extensions
Using extensions to do the repetition which makes for an easier syntax when repeating Strings, and using String.extend() to get faster evaluation.
extension String {
// Slower version
func repeatString(n: Int) -> String {
return Array(count: n, repeatedValue: self).joinWithSeparator("")
}
// Faster version
// benchmarked with a 1000 characters and 100 repeats the fast version is approx 500 000 times faster :-)
func repeatString2(n:Int) -> String {
var result = self
for _ in 1 ..< n {
result.appendContentsOf(self) // Note that String.appendContentsOf is up to 10 times faster than "result += self"
}
return result
}
}
print( "ha".repeatString(5) )
print( "he".repeatString2(5) )
- Output:
hahahahaha hehehehehe
To repeat a single character:
String(count:5, repeatedValue:"*" as Character)
Note that using the String version on a string of 1 Character, or the repeat single Character version is timewise close to the same. No point in using the Character version for efficiency (tested with repeating up to 100 000 times).
Bitwise Iterative Version
The following version is an enhanced version of the recursive ActionScript, where we're using bit operation along with iterative doubling of the string to get to the correctly repeated version of the text in the most effective manner without recursion. When benchmarked against the plain iterative version in previous section, this version is marginally better, but only my a very small percentage. The critical factor for making the repeat function effective when using larger strings (1000 characters) and multiple repeats (1000 repeats :-) ) was to to exchange the '+=' with 'String.extend' method.
extension String {
func repeatBiterative(count: Int) -> String {
var reduceCount = count
var result = ""
var doubled = self
while reduceCount != 0 {
if reduceCount & 1 == 1 {
result.appendContentsOf(doubled)
}
reduceCount >>= 1
if reduceCount != 0 {
doubled.appendContentsOf(doubled)
}
}
return result
}
}
"He".repeatBiterative(5)
- Output:
"HeHeHeHeHe"
Tailspin
'$:1..5 -> 'ha';' -> !OUT::write
- Output:
hahahahaha
Tcl
string repeat "ha" 5 ;# => hahahahaha
TorqueScript
--Eepos
function strRep(%str,%int)
{
for(%i = 0; %i < %int; %i++)
{
%rstr = %rstr@%str;
}
return %rstr;
}
Tosh
when flag clicked
set String to "meow"
set Count to 4
set Repeated to ""
repeat Count
set Repeated to (join (Repeated) (String))
end
stop this script
Transact-SQL
select REPLICATE( 'ha', 5 )
TUSCRIPT
$$ MODE TUSCRIPT
repeatstring=REPEAT ("ha",5)
UNIX Shell
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
Using repeat
len=12; str='='
repeat $len printf "$str"
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"
Ursala
#import nat
repeat = ^|DlSL/~& iota
#cast %s
example = repeat('ha',5)
output:
'hahahahaha'
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');
VBA
Repeat a string
Public Function RepeatStr(aString As String, aNumber As Integer) As String
Dim bString As String, i As Integer
bString = ""
For i = 1 To aNumber
bString = bString & aString
Next i
RepeatStr = bString
End Function
Debug.Print RepeatStr("ha", 5)
- Output:
hahahahaha
Note: "String(5, "ha") in VBA produces "hhhhh" (only the first character is repeated)!
An alternative method:
Public Function RepeatString(stText As String, iQty As Integer) As String
RepeatString = Replace(String(iQty, "x"), "x", stText)
End Function
Repeat a character
Debug.Print String(5, "x")
- Output:
xxxxx
VBScript
' VBScript has a String() function that can repeat a character a given number of times
' but this only works with single characters (or the 1st char of a string):
WScript.Echo String(10, "123") ' Displays "1111111111"
' To repeat a string of chars, you can use either of the following "hacks"...
WScript.Echo Replace(Space(10), " ", "Ha")
WScript.Echo Replace(String(10, "X"), "X", "Ha")
Vedit macro language
Ins_Text("ha", COUNT, 5)
Visual Basic
Repeat a string
Public Function StrRepeat(s As String, n As Integer) As String
Dim r As String, i As Integer
r = ""
For i = 1 To n
r = r & s
Next i
StrRepeat = r
End Function
Debug.Print StrRepeat("ha", 5)
- Output:
hahahahaha
An alternative method:
Public Function StrRepeat(sText As String, n As Integer) As String
StrRepeat = Replace(String(n, "*"), "*", sText)
End Function
Repeat a character
Debug.Print String(5, "x")
- Output:
xxxxx
Visual Basic .NET
Repeat a string
Debug.Print(Replace(Space(5), " ", "Ha"))
- Output:
HaHaHaHaHa
Repeat a character
Debug.Print(StrDup(5, "x"))
Debug.Print("".PadRight(5, "x"))
Debug.Print("".PadLeft(5, "x"))
- Output:
xxxxx xxxxx xxxxx
Visual FoxPro
Use the built in function REPLICATE(string, number):
? REPLICATE("HO", 3)
produces
HOHOHO
V (Vlang)
// Repeat a string, in V
// Tectonics: v run repeat-a-string.v
module main
import strings
// starts here
pub fn main() {
// A strings module function to repeat strings
println(strings.repeat_string("ha", 5))
// Another strings module function to repeat a byte
// This indexes the string to get the first byte of the rune array
println(strings.repeat("*"[0], 5))
}
- Output:
prompt$ v run rosetta/repeat-a-string.v hahahahaha *****
VBScript
replace(string(5,"@"),"@","hello")
- Output:
hellohellohellohellohello
Wart
def (s * n) :case (string? s)
with outstring
repeat n
pr s
("ha" * 5)
=> "hahahahaha"
Wortel
@join "" @rep 5 "ha" ; returns "hahahahaha"
As a function:
^(\@join "" @rep)
Wren
System.print("ha" * 5)
- Output:
hahahahaha
XPL0
cod T=12; int I; for I gets 1,5 do T(0,"ha")
- Output:
hahahahaha
Yorick
array("ha", 5)(sum)
Z80 Assembly
PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints the ascii code in the accumulator to the screen.
org &8000
ld b,5 ; repeat 5 times
loop:
call PrintImmediate
byte "ha",0
djnz loop
ret ; return to basic
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
PrintImmediate:
pop hl ; get the return address into HL, it's the start of the embedded string.
call PrintString
; inc hl ; if your strings are null-terminated you can omit this, since a 0 equals the "NOP" instruction
jp (hl) ; acts as a ret, returning execution to the instruction just after the embedded string.
PrintString:
ld a,(hl) ; read in a character from the string
or a ; if your strings are null-terminated you can use this as a shortcut, otherwise use the compare instruction
ret z ; exit once the terminator is reached.
call PrintChar ; BIOS call, all regs are preserved.
inc hl ; next char
jr PrintString ; back to start.
- Output:
hahahahaha
zig
At compile-time:
const laugh = "ha" ** 5;
Note that to achieve this at run-time in zig (in order to avoid hidden overflows) you must manage the memory yourself.
const std = @import("std");
const warn = std.debug.warn;
const Allocator = std.mem.Allocator;
fn repeat(s: []const u8, times: u16, allocator: *Allocator) ![]u8 {
const repeated = try allocator.alloc(u8, s.len*times);
var i: usize = 0;
while (i < s.len*times) : (i += 1) {
repeated[i] = s[i % 2];
}
return repeated;
}
pub fn main() !void {
const allocator = std.debug.global_allocator;
const ex = try repeat("ha", 5, allocator);
defer allocator.free(ex);
}
zkl
Same as Ruby
"ha" * 5 # --> "hahahahaha"
- Programming Tasks
- String manipulation
- 11l
- 360 Assembly
- 4DOS Batch
- 6502 Assembly
- 68000 Assembly
- 8080 Assembly
- 8th
- ABAP
- Action!
- ActionScript
- Ada
- Aime
- ALGOL 68
- Amazing Hopper
- APL
- AppleScript
- Applesoft BASIC
- Arturo
- AutoHotkey
- AutoIt
- AWK
- Babel
- BaCon
- BASIC
- BASIC256
- Chipmunk Basic
- GW-BASIC
- Minimal BASIC
- MSX Basic
- QBasic
- Quite BASIC
- True BASIC
- XBasic
- Yabasic
- Batch File
- BBC BASIC
- Beeswax
- Beef
- Befunge
- BQN
- Bracmat
- Brainf***
- Brat
- Burlesque
- C
- C sharp
- C++
- Ceylon
- Clipper
- Clojure
- COBOL
- ColdFusion
- Common Lisp
- Crystal
- D
- DCL
- Delphi
- DWScript
- Dyalect
- Déjà Vu
- E
- EasyLang
- ECL
- Ecstasy
- Egison
- Eiffel
- Elena
- Elixir
- Emacs Lisp
- Cl-lib
- Erlang
- ERRE
- Euphoria
- Explore
- F Sharp
- Factor
- Forth
- Fortran
- Free Pascal
- FreeBASIC
- Frink
- FutureBasic
- Gambas
- GAP
- Glee
- Go
- Groovy
- Harbour
- Haskell
- HicEst
- Icon
- Unicon
- Idris
- Inform 7
- Insitux
- IS-BASIC
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Kotlin
- LabVIEW
- Lambdatalk
- Lang
- Langur
- Lasso
- LFE
- Liberty BASIC
- Lingo
- LiveCode
- Logo
- Lua
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- Mercury
- Min
- MiniScript
- Mirah
- Monte
- MontiLang
- MUMPS
- Nanoquery
- Neko
- Nemerle
- NetRexx
- NewLISP
- Nim
- Objeck
- Objective-C
- OCaml
- Oforth
- OpenEdge/Progress
- OxygenBasic
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phixmonti
- PHP
- PicoLisp
- Pike
- PL/I
- Plain English
- Plorth
- PostScript
- PowerBASIC
- PowerShell
- Processing
- Processing Python mode
- Prolog
- Pure
- PureBasic
- Python
- Quackery
- R
- Racket
- Raku
- RapidQ
- REALbasic
- REBOL
- Red
- ReScript
- Retro
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- Scala
- Scheme
- Scratch
- Sed
- Seed7
- SenseTalk
- Sidef
- Sinclair ZX81 BASIC
- Smalltalk
- SNOBOL4
- Sparkling
- SQL
- SQL PL
- Standard ML
- Stata
- Suneido
- Swift
- Tailspin
- Tcl
- TorqueScript
- Tosh
- Transact-SQL
- TUSCRIPT
- UNIX Shell
- Ursala
- Vala
- VBA
- VBScript
- Vedit macro language
- Visual Basic
- Visual Basic .NET
- Visual FoxPro
- V (Vlang)
- Wart
- Wortel
- Wren
- XPL0
- Yorick
- Z80 Assembly
- Zig
- Zkl
- Pages with too many expensive parser function calls