Repeat a string: Difference between revisions

Content added Content deleted
m (→‎{{header|J}}: grammar)
m (syntax highlighting fixup automation)
Line 12: Line 12:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>print(‘ha’ * 5)</lang>
<syntaxhighlight lang="11l">print(‘ha’ * 5)</syntaxhighlight>


{{out}}
{{out}}
Line 20: Line 20:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Repeat a string - 19/04/2020
<syntaxhighlight lang="360asm">* Repeat a string - 19/04/2020
REPEATS CSECT
REPEATS CSECT
USING REPEATS,R13 base register
USING REPEATS,R13 base register
Line 62: Line 62:
PG DC CL80' ' pg
PG DC CL80' ' pg
REGEQU
REGEQU
END REPEATS </lang>
END REPEATS </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 70: Line 70:


=={{header|4DOS Batch}}==
=={{header|4DOS Batch}}==
<lang 4dos>gosub repeat ha 5
<syntaxhighlight lang="4dos">gosub repeat ha 5
echo %@repeat[*,5]
echo %@repeat[*,5]
quit
quit
Line 79: Line 79:
enddo
enddo
echo.
echo.
return</lang>
return</syntaxhighlight>
Output shows:
Output shows:
<pre>hahahahaha
<pre>hahahahaha
Line 85: Line 85:


=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
<lang 6502asm>CHROUT equ $FFD2 ;KERNAL call, prints the accumulator to the screen as an ascii value.
<syntaxhighlight lang="6502asm">CHROUT equ $FFD2 ;KERNAL call, prints the accumulator to the screen as an ascii value.


org $0801
org $0801
Line 127: Line 127:
TestStr:
TestStr:
db "HA",0</lang>
db "HA",0</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 143: Line 143:
=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
Easiest way to do this is with a loop.
Easiest way to do this is with a loop.
<lang 68000devpac>MOVE.W #5-1,D1
<syntaxhighlight lang="68000devpac">MOVE.W #5-1,D1
RepString:
RepString:
LEA A3, MyString
LEA A3, MyString
Line 154: Line 154:
MyString:
MyString:
DC.B "ha",0
DC.B "ha",0
even</lang>
even</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>"ha" 5 s:*
<syntaxhighlight lang="forth">"ha" 5 s:*
. cr</lang>
. cr</syntaxhighlight>
Output shows:
Output shows:
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>
Line 165: Line 165:
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}}
Line 177: Line 177:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>Proc Main()
<syntaxhighlight lang="action!">Proc Main()
byte REPEAT
byte REPEAT


Line 187: Line 187:
Do
Do


Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>
Line 197: Line 197:


===Iterative version===
===Iterative version===
<lang ActionScript>function repeatString(string:String, numTimes:uint):String
<syntaxhighlight lang="actionscript">function repeatString(string:String, numTimes:uint):String
{
{
var output:String = "";
var output:String = "";
Line 203: Line 203:
output += string;
output += string;
return output;
return output;
}</lang>
}</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.
<lang ActionScript>function repeatRecursive(string:String, numTimes:uint):String
<syntaxhighlight lang="actionscript">function repeatRecursive(string:String, numTimes:uint):String
{
{
if(numTimes == 0) return "";
if(numTimes == 0) return "";
Line 213: Line 213:
var tmp:String = repeatRecursive(string, numTimes/2);
var tmp:String = repeatRecursive(string, numTimes/2);
return tmp + tmp;
return tmp + tmp;
}</lang>
}</syntaxhighlight>


===Flex===
===Flex===
<lang ActionScript>import mx.utils.StringUtil;
<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 226: Line 226:
=={{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:
<lang Ada>with Ada.Strings.Fixed; use Ada.Strings.Fixed;
<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 232: Line 232:
begin
begin
Put_Line (5 * "ha");
Put_Line (5 * "ha");
end String_Multiplication;</lang>
end String_Multiplication;</syntaxhighlight>
Sample output:
Sample output:
<pre>
<pre>
Line 239: Line 239:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>call_n(5, o_text, "ha");</lang>
<syntaxhighlight lang="aime">call_n(5, o_text, "ha");</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68>print (5 * "ha")
<syntaxhighlight lang="algol68">print (5 * "ha")
</syntaxhighlight>
</lang>


=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#!/usr/bin/hopper
#!/usr/bin/hopper
#include <hopper.h>
#include <hopper.h>
Line 254: Line 254:
{"ha",5}replicate, println
{"ha",5}replicate, println
{0}return
{0}return
</syntaxhighlight>
</lang>
hahahahaha
hahahahaha
hahahahaha
hahahahaha
Line 260: Line 260:
=={{header|APL}}==
=={{header|APL}}==
Fill up a string of length 10 with 'ha':
Fill up a string of length 10 with 'ha':
<lang apl> 10⍴'ha'
<syntaxhighlight lang="apl"> 10⍴'ha'
hahahahaha</lang>
hahahahaha</syntaxhighlight>
Alternatively, define a function:
Alternatively, define a function:
<lang apl> REPEAT←{(⍺×⍴⍵)⍴⍵}
<syntaxhighlight lang="apl"> REPEAT←{(⍺×⍴⍵)⍴⍵}
5 REPEAT 'ha'
5 REPEAT 'ha'
hahahahaha</lang>
hahahahaha</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>set str to "ha"
<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</lang>
end repeat</syntaxhighlight>




Line 280: Line 280:


{{trans|JavaScript}}
{{trans|JavaScript}}
<lang AppleScript>replicate(5000, "ha")
<syntaxhighlight lang="applescript">replicate(5000, "ha")


-- Repetition by 'Egyptian multiplication' -
-- Repetition by 'Egyptian multiplication' -
Line 299: Line 299:
end repeat
end repeat
return out & dbl
return out & dbl
end replicate</lang>
end replicate</syntaxhighlight>


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang ApplesoftBasic>FOR I = 1 TO 5 : S$ = S$ + "HA" : NEXT
<syntaxhighlight lang="applesoftbasic">FOR I = 1 TO 5 : S$ = S$ + "HA" : NEXT


? "X" SPC(20) "X"</lang>
? "X" SPC(20) "X"</syntaxhighlight>
Output:
Output:
<pre>X X</pre>
<pre>X X</pre>


=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>print repeat "ha" 5</lang>
<syntaxhighlight lang="rebol">print repeat "ha" 5</syntaxhighlight>


{{out}}
{{out}}
Line 316: Line 316:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % Repeat("ha",5)
<syntaxhighlight lang="autohotkey">MsgBox % Repeat("ha",5)


Repeat(String,Times)
Repeat(String,Times)
Line 323: Line 323:
Output .= String
Output .= String
Return Output
Return Output
}</lang>
}</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>#include <String.au3>
<syntaxhighlight lang="autoit">#include <String.au3>


ConsoleWrite(_StringRepeat("ha", 5) & @CRLF)</lang>
ConsoleWrite(_StringRepeat("ha", 5) & @CRLF)</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>function repeat( str, n, rep, i )
<syntaxhighlight lang="awk">function repeat( str, n, rep, i )
{
{
for( ; i<n; i++ )
for( ; i<n; i++ )
Line 340: Line 340:
BEGIN {
BEGIN {
print repeat( "ha", 5 )
print repeat( "ha", 5 )
}</lang>
}</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
<lang babel>main: { "ha" 5 print_repeat }
<syntaxhighlight lang="babel">main: { "ha" 5 print_repeat }


print_repeat!: { <- { dup << } -> times }</lang>
print_repeat!: { <- { dup << } -> times }</syntaxhighlight>
Outputs:
Outputs:
<lang babel>hahahahaha</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:
<lang qbasic>DOTIMES 5
<syntaxhighlight lang="qbasic">DOTIMES 5
s$ = s$ & "ha"
s$ = s$ & "ha"
DONE
DONE
PRINT s$</lang>
PRINT s$</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 361: Line 361:
</pre>
</pre>
To repeat one single character:
To repeat one single character:
<lang qbasic>PRINT FILL$(5, ASC("x"))</lang>
<syntaxhighlight lang="qbasic">PRINT FILL$(5, ASC("x"))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 370: Line 370:
=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang BASIC256>function StringRepeat$ (s$, n)
<syntaxhighlight lang="basic256">function StringRepeat$ (s$, n)
cad$ = ""
cad$ = ""
for i = 1 to n
for i = 1 to n
Line 381: Line 381:
print StringRepeat$("ha", 5)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
print StringRepeat$("*", 5)
end</lang>
end</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
<lang QBasic>FUNCTION StringRepeat$ (s$, n)
<syntaxhighlight lang="qbasic">FUNCTION StringRepeat$ (s$, n)
cad$ = ""
cad$ = ""
FOR i = 1 TO n
FOR i = 1 TO n
Line 395: Line 395:
PRINT StringRepeat$("ha", 5)
PRINT StringRepeat$("ha", 5)
PRINT StringRepeat$("*", 5)
PRINT StringRepeat$("*", 5)
END</lang>
END</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>FUNCTION StringRepeat$ (s$, n)
<syntaxhighlight lang="qbasic">FUNCTION StringRepeat$ (s$, n)
LET cad$ = ""
LET cad$ = ""
FOR i = 1 TO n
FOR i = 1 TO n
Line 409: Line 409:
PRINT StringRepeat$("ha", 5)
PRINT StringRepeat$("ha", 5)
PRINT StringRepeat$("*", 5)
PRINT StringRepeat$("*", 5)
END</lang>
END</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>sub StringRepeat$ (s$, n)
<syntaxhighlight lang="yabasic">sub StringRepeat$ (s$, n)
cad$ = ""
cad$ = ""
for i = 1 to n
for i = 1 to n
Line 423: Line 423:
print StringRepeat$("ha", 5)
print StringRepeat$("ha", 5)
print StringRepeat$("*", 5)
print StringRepeat$("*", 5)
end</lang>
end</syntaxhighlight>




=={{header|Batch File}}==
=={{header|Batch File}}==
Commandline implementation
Commandline implementation
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
if "%2" equ "" goto fail
if "%2" equ "" goto fail
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
Line 435: Line 435:
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</lang>
:fail</syntaxhighlight>


'Function' version
'Function' version
<lang dos>@echo off
<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 447: Line 447:
set "c=%c%+=1"
set "c=%c%+=1"
if /i _"%c%"==_"%d%" (exit /b)
if /i _"%c%"==_"%d%" (exit /b)
goto :a</lang>
goto :a</syntaxhighlight>


'Function' version 2
'Function' version 2
<lang dos>@echo off
<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 462: Line 462:
@GOTO:EOF
@GOTO:EOF


:END</lang>
:END</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
<lang bbcbasic> PRINT STRING$(5, "ha")</lang>
<syntaxhighlight lang="bbcbasic"> PRINT STRING$(5, "ha")</syntaxhighlight>


=={{header|beeswax}}==
=={{header|beeswax}}==
<lang beeswax> p <
<syntaxhighlight lang="beeswax"> p <
p0~1<}~< d@<
p0~1<}~< d@<
_VT@1~>yg~9PKd@M'd;</lang>
_VT@1~>yg~9PKd@M'd;</syntaxhighlight>




Line 484: Line 484:


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang Befunge>v> ">:#,_v
<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#^_@</lang>
v p00&p0-1g00+4*65< >00g1-:00p#^_@</syntaxhighlight>
Input sample:
Input sample:
<pre>ha05</pre>
<pre>ha05</pre>
Line 499: Line 499:
<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.
<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.


<lang bqn>Repeat ← ×⟜≠ ⥊ ⊢
<syntaxhighlight lang="bqn">Repeat ← ×⟜≠ ⥊ ⊢


•Show 5 Repeat "Hello"</lang><lang>"HelloHelloHelloHelloHello"</lang>
•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.


<lang bracmat>(repeat=
<syntaxhighlight lang="bracmat">(repeat=
string N rep
string N rep
. !arg:(?string.?N)
. !arg:(?string.?N)
Line 513: Line 513:
' (!N+-1:>0:?N&!string !rep:?rep)
' (!N+-1:>0:?N&!string !rep:?rep)
& str$!rep
& str$!rep
);</lang>
);</syntaxhighlight>


<pre> repeat$(ha.5)
<pre> repeat$(ha.5)
Line 520: Line 520:
=={{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.
<lang bf>+++++ +++++ init first as 10 counter
<syntaxhighlight lang="bf">+++++ +++++ init first as 10 counter
[-> +++++ +++++<] we add 10 to second each loopround
[-> +++++ +++++<] we add 10 to second each loopround


Line 528: Line 528:


and a newline because I'm kind and it looks good
and a newline because I'm kind and it looks good
+++++ +++++ +++ . --- .</lang>
+++++ +++++ +++ . --- .</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>p "ha" * 5 #Prints "hahahahaha"</lang>
<syntaxhighlight lang="brat">p "ha" * 5 #Prints "hahahahaha"</syntaxhighlight>


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 'h5?*
blsq ) 'h5?*
"hhhhh"
"hhhhh"
blsq ) "ha"5.*\[
blsq ) "ha"5.*\[
"hahahahaha"
"hahahahaha"
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 563: Line 563:
free(result);
free(result);
return 0;
return 0;
}</lang>
}</syntaxhighlight>
A variation.
A variation.
<lang c>...
<syntaxhighlight lang="c">...
char *string_repeat(const char *str, int n)
char *string_repeat(const char *str, int n)
{
{
Line 577: Line 577:
while (pa>=dest) *pa-- = *pb--;
while (pa>=dest) *pa-- = *pb--;
return dest;
return dest;
}</lang>
}</syntaxhighlight>


To repeat a single character
To repeat a single character
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 596: Line 596:
free(result);
free(result);
return 0;
return 0;
}</lang>
}</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}}==
<lang csharp>string s = "".PadLeft(5, 'X').Replace("X", "ha");</lang>
<syntaxhighlight lang="csharp">string s = "".PadLeft(5, 'X').Replace("X", "ha");</syntaxhighlight>
or (with .NET 2+)
or (with .NET 2+)
<lang csharp>string s = new String('X', 5).Replace("X", "ha");</lang>
<syntaxhighlight lang="csharp">string s = new String('X', 5).Replace("X", "ha");</syntaxhighlight>
or (with .NET 2+)
or (with .NET 2+)
<lang csharp>string s = String.Join("ha", new string[5 + 1]);</lang>
<syntaxhighlight lang="csharp">string s = String.Join("ha", new string[5 + 1]);</syntaxhighlight>
or (with .NET 4+)
or (with .NET 4+)
<lang csharp>string s = String.Concat(Enumerable.Repeat("ha", 5));</lang>
<syntaxhighlight lang="csharp">string s = String.Concat(Enumerable.Repeat("ha", 5));</syntaxhighlight>


To repeat a single character:
To repeat a single character:
<lang csharp>string s = "".PadLeft(5, '*');</lang>
<syntaxhighlight lang="csharp">string s = "".PadLeft(5, '*');</syntaxhighlight>
or (with .NET 2+)
or (with .NET 2+)
<lang csharp>string s = new String('*', 5);</lang>
<syntaxhighlight lang="csharp">string s = new String('*', 5);</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>


Line 629: Line 629:
std::cout << repeat( "Ha" , 5 ) << std::endl ;
std::cout << repeat( "Ha" , 5 ) << std::endl ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>


To repeat a single character:
To repeat a single character:
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>


Line 638: Line 638:
std::cout << std::string( 5, '*' ) << std::endl ;
std::cout << std::string( 5, '*' ) << std::endl ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>


=== recursive version ===
=== recursive version ===
<lang cpp>#include <string>
<syntaxhighlight lang="cpp">#include <string>
#include <iostream>
#include <iostream>
Line 656: Line 656:
std::cout << repeat( "Ha" , 5 ) << std::endl ;
std::cout << repeat( "Ha" , 5 ) << std::endl ;
return 0 ;
return 0 ;
}</lang>
}</syntaxhighlight>


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void repeatAString() {
<syntaxhighlight lang="ceylon">shared void repeatAString() {
print("ha".repeat(5));
print("ha".repeat(5));
}</lang>
}</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)
<lang visualfoxpro> Replicate( "Ha", 5 )</lang>
<syntaxhighlight lang="visualfoxpro"> Replicate( "Ha", 5 )</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang lisp>(apply str (repeat 5 "ha"))</lang>
<syntaxhighlight lang="lisp">(apply str (repeat 5 "ha"))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Virtually a one-liner.
Virtually a one-liner.
<lang cobol>IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. REPEAT-PROGRAM.
PROGRAM-ID. REPEAT-PROGRAM.
DATA DIVISION.
DATA DIVISION.
Line 680: Line 680:
MOVE ALL 'ha' TO HAHA.
MOVE ALL 'ha' TO HAHA.
DISPLAY HAHA.
DISPLAY HAHA.
STOP RUN.</lang>
STOP RUN.</syntaxhighlight>
{{out}}
{{out}}
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>


=={{header|ColdFusion}}==
=={{header|ColdFusion}}==
<lang cfm>
<syntaxhighlight lang="cfm">
<cfset word = 'ha'>
<cfset word = 'ha'>
<Cfset n = 5>
<Cfset n = 5>
Line 691: Line 691:
<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}}==
<lang lisp>(defun repeat-string (n string)
<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))))</lang>
(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:


<lang lisp>(defun repeat-string (n string
<syntaxhighlight lang="lisp">(defun repeat-string (n string
&aux
&aux
(len (length string))
(len (length string))
Line 708: Line 708:
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)</lang>
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:
<lang lisp>(defun repeat-string (n string)
<syntaxhighlight lang="lisp">(defun repeat-string (n string)
(format nil "~V@{~a~:*~}" n string))</lang>
(format nil "~V@{~a~:*~}" n string))</syntaxhighlight>




<lang lisp>(princ (repeat-string 5 "hi"))</lang>
<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>:
<lang lisp>(make-string 5 :initial-element #\X)</lang>
<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>
<pre>hahahahaha</pre>
Line 732: Line 732:
=={{header|D}}==
=={{header|D}}==
Repeating a string:
Repeating a string:
<lang d>import std.stdio, std.array;
<syntaxhighlight lang="d">import std.stdio, std.array;


void main() {
void main() {
writeln("ha".replicate(5));
writeln("ha".replicate(5));
}</lang>
}</syntaxhighlight>
Repeating a character with vector operations:
Repeating a character with vector operations:
<lang d>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


void main() {
void main() {
Line 745: Line 745:
chars[] = '*'; // set all characters in the string to '*'
chars[] = '*'; // set all characters in the string to '*'
writeln(chars);
writeln(chars);
}</lang>
}</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;
<lang DCL>$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" )
<syntaxhighlight lang="dcl">$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" )
$ write sys$output f$fao( "!12*d" )</lang>
$ 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 758: Line 758:
=={{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 768: Line 768:


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 786: Line 786:
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 Delphi>StrUtils.DupeString</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 dyalect>String.Repeat("ha", 5)</lang>
<syntaxhighlight lang="dyalect">String.Repeat("ha", 5)</syntaxhighlight>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>!. concat( rep 5 "ha" )</lang>
<syntaxhighlight lang="dejavu">!. concat( rep 5 "ha" )</syntaxhighlight>
{{out}}
{{out}}
<pre>"hahahahaha"</pre>
<pre>"hahahahaha"</pre>


=={{header|E}}==
=={{header|E}}==
<lang e>"ha" * 5</lang>
<syntaxhighlight lang="e">"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'</lang>
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 833: Line 833:


RepeatString('ha',3);
RepeatString('ha',3);
RepeatString('Who',2);</lang>
RepeatString('Who',2);</syntaxhighlight>


=={{header|Egison}}==
=={{header|Egison}}==
<lang egison>
<syntaxhighlight lang="egison">
(S.concat (take 5 (repeat1 "ha")))
(S.concat (take 5 (repeat1 "ha")))
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<lang eiffel>
<syntaxhighlight lang="eiffel">
repeat_string(a_string: STRING; times: INTEGER): STRING
repeat_string(a_string: STRING; times: INTEGER): STRING
require
require
Line 848: Line 848:
Result := a_string.multiply(times)
Result := a_string.multiply(times)
end
end
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;
import extensions'text;
import extensions'text;
Line 859: Line 859:
{
{
var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter())
var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter())
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang 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:


<lang lisp>(apply 'concat (make-list 5 "ha"))</lang>
<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 lisp>(make-string 5 ?x)</lang>
<syntaxhighlight lang="lisp">(make-string 5 ?x)</syntaxhighlight>


The <code>cl-loop</code> macro can repeat and concatenate:
The <code>cl-loop</code> macro can repeat and concatenate:


{{libheader|cl-lib}}
{{libheader|cl-lib}}
<lang lisp>(require 'cl-lib)
<syntaxhighlight lang="lisp">(require 'cl-lib)
(cl-loop repeat 5 concat "ha")</lang>
(cl-loop repeat 5 concat "ha")</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>repeat(X,N) ->
<syntaxhighlight lang="erlang">repeat(X,N) ->
lists:flatten(lists:duplicate(N,X)).</lang>
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 895: Line 895:
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>.
Line 902: Line 902:
=={{header|Euphoria}}==
=={{header|Euphoria}}==
A simple loop will do:
A simple loop will do:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
sequence s = ""
sequence s = ""
for i = 1 to 5 do s &= "ha" end for
for i = 1 to 5 do s &= "ha" end for
Line 908: Line 908:


hahahahaha
hahahahaha
</syntaxhighlight>
</lang>


For repeating a single character:
For repeating a single character:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
sequence s = repeat('*',5)
sequence s = repeat('*',5)


*****
*****
</syntaxhighlight>
</lang>


For repeating a string or sequence of numbers:
For repeating a string or sequence of numbers:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/console.e -- for display
include std/console.e -- for display
include std/sequence.e -- for repeat_pattern
include std/sequence.e -- for repeat_pattern
Line 928: Line 928:
hahahahaha
hahahahaha
{1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}
{1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}
</syntaxhighlight>
</lang>


But wait, here's another way:
But wait, here's another way:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
include std/console.e -- for display
include std/console.e -- for display
include std/sequence.e -- for flatten
include std/sequence.e -- for flatten
sequence s = flatten(repeat("ha",5))
sequence s = flatten(repeat("ha",5))
display(s)
display(s)
</syntaxhighlight>
</lang>


note: repeat creates a sequence of ha's as shown below; flatten concatenates them.
note: repeat creates a sequence of ha's as shown below; flatten concatenates them.
<syntaxhighlight lang="euphoria">
<lang Euphoria>
{
{
"ha",
"ha",
Line 947: Line 947:
"ha"
"ha"
}
}
</syntaxhighlight>
</lang>


=={{header|Explore}}==
=={{header|Explore}}==
Line 955: Line 955:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>> String.replicate 5 "ha";;
<syntaxhighlight lang="fsharp">> String.replicate 5 "ha";;
val it : string = "hahahahaha"</lang>
val it : string = "hahahahaha"</syntaxhighlight>
Or
Or
<lang fsharp>> String.Concat( Array.create 5 "ha" );;
<syntaxhighlight lang="fsharp">> String.Concat( Array.create 5 "ha" );;
val it : string = "hahahahaha"</lang>
val it : string = "hahahahaha"</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: repeat-string ( str n -- str' ) swap <repetition> concat ;
<syntaxhighlight lang="factor">: repeat-string ( str n -- str' ) swap <repetition> concat ;


"ha" 5 repeat-string print</lang>
"ha" 5 repeat-string print</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: place-n { src len dest n -- }
<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</lang>
pad count type \ hahahahaha</syntaxhighlight>
The same code without the use of locals:
The same code without the use of locals:
<lang forth>
<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 981: Line 981:


s" ha" pad 5 place-n
s" ha" pad 5 place-n
pad count type \ hahahahaha</lang>
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:
<lang forth>pad 10 char * fill \ repeat a single character
<syntaxhighlight lang="forth">pad 10 char * fill \ repeat a single character
pad 10 type \ **********</lang>
pad 10 type \ **********</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with |Fortran|90 and later}}
{{works with |Fortran|90 and later}}
<lang fortran>program test_repeat
<syntaxhighlight lang="fortran">program test_repeat


write (*, '(a)') repeat ('ha', 5)
write (*, '(a)') repeat ('ha', 5)


end program test_repeat</lang>
end program test_repeat</syntaxhighlight>
Output:
Output:
hahahahaha
hahahahaha


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
<lang pascal>strUtils.dupeString('ha', 5)</lang>
<syntaxhighlight lang="pascal">strUtils.dupeString('ha', 5)</syntaxhighlight>
Repetition of a single character:
Repetition of a single character:
<lang pascal>stringOfChar('*', 5)</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 pascal>space(5)</lang>
<syntaxhighlight lang="pascal">space(5)</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<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 1,032: Line 1,032:
Print
Print
Print "Press any key to quit program"
Print "Press any key to quit program"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,042: Line 1,042:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
println[repeat["ha", 5]]
println[repeat["ha", 5]]
</syntaxhighlight>
</lang>


=={{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</lang>
End</syntaxhighlight>


Output = hahahahaha
Output = hahahahaha


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>Concatenation(ListWithIdenticalEntries(10, "BOB "));
<syntaxhighlight lang="gap">Concatenation(ListWithIdenticalEntries(10, "BOB "));
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "</lang>
"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "</syntaxhighlight>


=={{header|Glee}}==
=={{header|Glee}}==
<lang glee>'*' %% 5</lang>
<syntaxhighlight lang="glee">'*' %% 5</syntaxhighlight>


<lang glee>'ha' => Str;
<syntaxhighlight lang="glee">'ha' => Str;
Str# => Len;
Str# => Len;
1..Len %% (Len * 5) => Idx;
1..Len %% (Len * 5) => Idx;
Str [Idx] $;</lang>
Str [Idx] $;</syntaxhighlight>


<lang glee>'ha'=>S[1..(S#)%%(S# *5)]</lang>
<syntaxhighlight lang="glee">'ha'=>S[1..(S#)%%(S# *5)]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>fmt.Println(strings.Repeat("ha", 5)) // ==> "hahahahaha"</lang>
<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:
<lang go>fmt.Println(strings.Repeat(string('h'), 5)) // prints hhhhh</lang>
<syntaxhighlight lang="go">fmt.Println(strings.Repeat(string('h'), 5)) // prints hhhhh</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy> println 'ha' * 5</lang>
<syntaxhighlight lang="groovy"> println 'ha' * 5</syntaxhighlight>


=={{header|Harbour}}==
=={{header|Harbour}}==
<lang visualfoxpro>? Replicate( "Ha", 5 )</lang>
<syntaxhighlight lang="visualfoxpro">? Replicate( "Ha", 5 )</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
For a string of finite length:
For a string of finite length:
<lang haskell>concat $ replicate 5 "ha"</lang>
<syntaxhighlight lang="haskell">concat $ replicate 5 "ha"</syntaxhighlight>


Or with list-monad (a bit obscure):
Or with list-monad (a bit obscure):
<lang haskell>[1..5] >> "ha"</lang>
<syntaxhighlight lang="haskell">[1..5] >> "ha"</syntaxhighlight>


Or with Control.Applicative:
Or with Control.Applicative:
<lang haskell>[1..5] *> "ha"</lang>
<syntaxhighlight lang="haskell">[1..5] *> "ha"</syntaxhighlight>


For an infinitely long string:
For an infinitely long string:
<lang haskell>cycle "ha"</lang>
<syntaxhighlight lang="haskell">cycle "ha"</syntaxhighlight>


To repeat a single character:
To repeat a single character:
<lang haskell>replicate 5 '*'</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''':
<lang haskell>repString :: String -> Int -> String
<syntaxhighlight lang="haskell">repString :: String -> Int -> String
repString s n =
repString s n =
let rep x = xs
let rep x = xs
Line 1,106: Line 1,106:


main :: IO ()
main :: IO ()
main = print $ repString "ha" 5</lang>
main = print $ repString "ha" 5</syntaxhighlight>
{{Out}}
{{Out}}
<pre>"hahahahaha"</pre>
<pre>"hahahahaha"</pre>
Line 1,112: Line 1,112:
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):


<lang haskell>import Data.Tuple (swap)
<syntaxhighlight lang="haskell">import Data.Tuple (swap)
import Data.List (unfoldr)
import Data.List (unfoldr)
import Control.Monad (join)
import Control.Monad (join)
Line 1,136: Line 1,136:
-- TEST -----------------------------------------------------------------------
-- TEST -----------------------------------------------------------------------
main :: IO ()
main :: IO ()
main = print $ repString 500 "ha"</lang>
main = print $ repString 500 "ha"</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>CHARACTER out*20
<syntaxhighlight lang="hicest">CHARACTER out*20


EDIT(Text=out, Insert="ha", DO=5)</lang>
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.
<lang Icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
write(repl(integer(!args) | 5))
write(repl(integer(!args) | 5))
end</lang>
end</syntaxhighlight>
If it weren't, one way to write it is:
If it weren't, one way to write it is:
<lang Icon>procedure repl(s, n)
<syntaxhighlight lang="icon">procedure repl(s, n)
every (ns := "") ||:= |s\(0 <= n)
every (ns := "") ||:= |s\(0 <= n)
return ns
return ns
end</lang>
end</syntaxhighlight>


=={{header|Idris}}==
=={{header|Idris}}==
<lang Idris>strRepeat : Nat -> String -> String
<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 1,161: Line 1,161:
chrRepeat : Nat -> Char -> String
chrRepeat : Nat -> Char -> String
chrRepeat Z c = ""
chrRepeat Z c = ""
chrRepeat (S n) c = strCons c $ chrRepeat n c</lang>
chrRepeat (S n) c = strCons c $ chrRepeat n c</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
<lang inform7>Home is a room.
<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 1,174: Line 1,174:
When play begins:
When play begins:
say "ha" repeated 5 times;
say "ha" repeated 5 times;
end the story.</lang>
end the story.</syntaxhighlight>


=={{header|IS-BASIC}}==
=={{header|IS-BASIC}}==
<lang IS-BASIC> 10 PRINT STRING$("ha",5)
<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 1,184: Line 1,184:
130 NEXT
130 NEXT
140 LET STRING$=ST$
140 LET STRING$=ST$
150 END DEF</lang>
150 END DEF</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j> 5 # '*' NB. repeat each item 5 times
<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 1,194: Line 1,194:
hahahahaha
hahahahaha
5 ;@# < 'ha' NB. using boxing to treat the array as a whole
5 ;@# < 'ha' NB. using boxing to treat the array as a whole
hahahahaha</lang>
hahahahaha</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
Line 1,201: Line 1,201:
There's no method or operator to do this in Java, so you have to do it yourself.
There's no method or operator to do this in Java, so you have to do it yourself.


<lang java5>public static String repeat(String str, int times) {
<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 1,210: Line 1,210:
public static void main(String[] args) {
public static void main(String[] args) {
System.out.println(repeat("ha", 5));
System.out.println(repeat("ha", 5));
}</lang>
}</syntaxhighlight>


Or even shorter:
Or even shorter:


<lang java5>public static String repeat(String str, int times) {
<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);
}</lang>
}</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 1,223: Line 1,223:
====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.
<lang javascript>String.prototype.repeat = function(n) {
<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</lang>
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:


<lang javascript>
<syntaxhighlight lang="javascript">
console.log("ha".repeat(5)); // hahahahaha</lang>
console.log("ha".repeat(5)); // hahahahaha</syntaxhighlight>


====Repetition by Egyptian multiplication====
====Repetition by Egyptian multiplication====
Line 1,239: Line 1,239:
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.


<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,257: Line 1,257:


return replicate(5000, "ha")
return replicate(5000, "ha")
})();</lang>
})();</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'''
<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
'use strict';
'use strict';


Line 1,287: Line 1,287:
// TEST -------------------------------------------------------------------
// TEST -------------------------------------------------------------------
return repeat(5, 'ha');
return repeat(5, 'ha');
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>


=={{header|jq}}==
=={{header|jq}}==
<lang jq>"a " * 3' # => "a a a "</lang>
<syntaxhighlight lang="jq">"a " * 3' # => "a a a "</syntaxhighlight>


Note that if the integer multiplicand is 0, then the result is null.
Note that if the integer multiplicand is 0, then the result is null.
Line 1,299: Line 1,299:
{{works with|Julia|1.0}}
{{works with|Julia|1.0}}


<lang julia>@show "ha" ^ 5
<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)</lang>
@show repeat("ha", 5)</syntaxhighlight>


=={{header|K}}==
=={{header|K}}==


<syntaxhighlight lang="k">
<lang k>
,/5#,"ha"
,/5#,"ha"
"hahahahaha"
"hahahahaha"
Line 1,312: Line 1,312:
5#"*"
5#"*"
"*****"
"*****"
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>fun main(args: Array<String>) {
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
println("ha".repeat(5))
println("ha".repeat(5))
}</lang>
}</syntaxhighlight>
Or more fancy:
Or more fancy:
<lang scala>operator fun String.times(n: Int) = this.repeat(n)
<syntaxhighlight lang="scala">operator fun String.times(n: Int) = this.repeat(n)


fun main(args: Array<String>) = println("ha" * 5)</lang>
fun main(args: Array<String>) = println("ha" * 5)</syntaxhighlight>


=={{header|LabVIEW}}==
=={{header|LabVIEW}}==
Line 1,328: Line 1,328:


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang="scheme">
{S.map {lambda {_} ha} {S.serie 1 10}}
{S.map {lambda {_} ha} {S.serie 1 10}}
-> ha ha ha ha ha ha ha ha ha ha
-> ha ha ha ha ha ha ha ha ha ha
Line 1,351: Line 1,351:
{repeat ha 10}
{repeat ha 10}
-> hahahahahahahahahahaha
-> hahahahahahahahahahaha
</syntaxhighlight>
</lang>


=={{header|langur}}==
=={{header|langur}}==
This example looks like Perl, but the x operator doesn't just multiply strings in langur.
This example looks like Perl, but the x operator doesn't just multiply strings in langur.
<lang langur>"ha" x 5</lang>
<syntaxhighlight lang="langur">"ha" x 5</syntaxhighlight>


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>'ha'*5 // hahahahaha</lang>
<syntaxhighlight lang="lasso">'ha'*5 // hahahahaha</syntaxhighlight>


<lang Lasso>loop(5) => {^ 'ha' ^} // hahahahaha</lang>
<syntaxhighlight lang="lasso">loop(5) => {^ 'ha' ^} // hahahahaha</syntaxhighlight>


=={{header|LFE}}==
=={{header|LFE}}==
<lang lisp>
<syntaxhighlight lang="lisp">
(string:copies '"ha" 5)
(string:copies '"ha" 5)
</syntaxhighlight>
</lang>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>a$ ="ha "
<syntaxhighlight lang="lb">a$ ="ha "
print StringRepeat$( a$, 5)
print StringRepeat$( a$, 5)


Line 1,379: Line 1,379:
next i
next i
StringRepeat$ =o$
StringRepeat$ =o$
end function</lang>
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.
<lang lingo>on rep (str, n)
<syntaxhighlight lang="lingo">on rep (str, n)
res = ""
res = ""
repeat with i = 1 to n
repeat with i = 1 to n
Line 1,389: Line 1,389:
end repeat
end repeat
return res
return res
end</lang>
end</syntaxhighlight>
<lang lingo>put rep("ha", 5)
<syntaxhighlight lang="lingo">put rep("ha", 5)
-- "hahahahaha"</lang>
-- "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”...
<lang lingo>put bytearray(5, chartonum("*")).readRawString(5)
<syntaxhighlight lang="lingo">put bytearray(5, chartonum("*")).readRawString(5)
-- "*****"</lang>
-- "*****"</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
<lang liveCode>on mouseUp
<syntaxhighlight lang="livecode">on mouseUp
put repeatString("ha", 5)
put repeatString("ha", 5)
end mouseUp
end mouseUp
Line 1,406: Line 1,406:
end repeat
end repeat
return t
return t
end repeatString</lang>
end repeatString</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to copies :n :thing [:acc "||]
<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</lang>
end</syntaxhighlight>
or using cascade:
or using cascade:
<lang logo>show cascade 5 [combine "ha ?] "|| ; hahahahaha</lang>
<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.


<lang logo>to copies :n :thing :acc
<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 "||</lang>
print copies 5 "ha "||</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end</lang>
<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 lua>string.rep(s,n)</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,441: Line 1,441:


"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,449: Line 1,449:
> 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.


Line 1,461: Line 1,461:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>(* solution 1 *)
<syntaxhighlight lang="mathematica">(* solution 1 *)
rep[n_Integer,s_String]:=Apply[StringJoin,ConstantArray[s,{n}]]
rep[n_Integer,s_String]:=Apply[StringJoin,ConstantArray[s,{n}]]
(* solution 2 -- @@ is the infix form of Apply[] *)
(* solution 2 -- @@ is the infix form of Apply[] *)
rep[n_Integer,s_String]:=StringJoin@@Table[s,{n}]
rep[n_Integer,s_String]:=StringJoin@@Table[s,{n}]
(* solution 3 -- demonstrating another of the large number of looping constructs available *)
(* solution 3 -- demonstrating another of the large number of looping constructs available *)
rep[n_Integer,s_String]:=Nest[StringJoin[s, #] &,s,n-1]</lang>
rep[n_Integer,s_String]:=Nest[StringJoin[s, #] &,s,n-1]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang MATLAB>function S = repeat(s , n)
<syntaxhighlight lang="matlab">function S = repeat(s , n)
S = repmat(s , [1,n]) ;
S = repmat(s , [1,n]) ;
return</lang>
return</syntaxhighlight>


Note 1: The repetition is returned, not displayed.
Note 1: The repetition is returned, not displayed.
Line 1,478: Line 1,478:


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>"$*"(s, n) := apply(sconcat, makelist(s, n))$
<syntaxhighlight lang="maxima">"$*"(s, n) := apply(sconcat, makelist(s, n))$
infix("$*")$
infix("$*")$


"abc" $* 5;
"abc" $* 5;
/* "abcabcabcabcabc" */</lang>
/* "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.


<lang Mercury>:- module repeat.
<syntaxhighlight lang="mercury">:- module repeat.
:- interface.
:- interface.
:- import_module string, char, int.
:- import_module string, char, int.
Line 1,512: Line 1,512:
print(Stream, String, !S),
print(Stream, String, !S),
printn(Stream, N - 1, String, !S)
printn(Stream, N - 1, String, !S)
; true ).</lang>
; true ).</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>"ha" 5 repeat print</lang>
<syntaxhighlight lang="min">"ha" 5 repeat print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,523: Line 1,523:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>str = "Lol"
<syntaxhighlight lang="miniscript">str = "Lol"
print str * 5</lang>
print str * 5</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,531: Line 1,531:


=={{header|Mirah}}==
=={{header|Mirah}}==
<lang mirah>x = StringBuilder.new
<syntaxhighlight lang="mirah">x = StringBuilder.new


5.times do
5.times do
Line 1,537: Line 1,537:
end
end


puts x # ==> "hahahahaha"</lang>
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 MontiLang>|ha| 5 * PRINT .</lang>
<syntaxhighlight lang="montilang">|ha| 5 * PRINT .</syntaxhighlight>
Or with a loop
Or with a loop
<lang MontiLang>FOR 5
<syntaxhighlight lang="montilang">FOR 5
|ha| OUT .
|ha| OUT .
ENDFOR || PRINT .</lang>
ENDFOR || PRINT .</syntaxhighlight>


Or ...
Or ...


<lang MontiLang>|ha| FOR 5 OUT ENDFOR . || PRINT .</lang>
<syntaxhighlight lang="montilang">|ha| FOR 5 OUT ENDFOR . || PRINT .</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>RPTSTR(S,N)
<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,566: Line 1,566:
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.
<lang Nanoquery>"ha" * 5</lang>
<syntaxhighlight lang="nanoquery">"ha" * 5</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<lang actionscript>/* Repeat a string, in 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,591: Line 1,591:
}
}


$print(srep("ha", 5), "\n")</lang>
$print(srep("ha", 5), "\n")</syntaxhighlight>


{{out}}
{{out}}
Line 1,600: Line 1,600:
=={{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).
<lang Nemerle>using System;
<syntaxhighlight lang="nemerle">using System;
using System.Console;
using System.Console;


Line 1,617: Line 1,617:


}
}
}</lang>
}</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:
<lang NetRexx>/* NetRexx */
<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:


<lang NetRexx>/* NetRexx */
<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,640: Line 1,640:
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}}==
<lang NewLISP>(dup "ha" 5)</lang>
<syntaxhighlight lang="newlisp">(dup "ha" 5)</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils
<syntaxhighlight lang="nim">import strutils


# Repeat a char.
# Repeat a char.
Line 1,652: Line 1,652:


# Repeat a string.
# Repeat a string.
echo repeat("ha", 5) # -> "hahahahaha".</lang>
echo repeat("ha", 5) # -> "hahahahaha".</syntaxhighlight>


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Repeat {
class Repeat {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 1,670: Line 1,670:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
Line 1,679: Line 1,679:
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.


<lang objc>@interface NSString (RosettaCodeAddition)
<syntaxhighlight lang="objc">@interface NSString (RosettaCodeAddition)
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times;
- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times;
@end
@end
Line 1,687: Line 1,687:
return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];
return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];
}
}
@end</lang>
@end</syntaxhighlight>


Now, let's put it to use:
Now, let's put it to use:
<lang objc> // Instantiate an NSString by sending an NSString literal our new
<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);</lang>
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.
<lang ocaml>let string_repeat s n =
<syntaxhighlight lang="ocaml">let string_repeat s n =
let s = Bytes.of_string s in
let s = Bytes.of_string s in
let len = Bytes.length s in
let len = Bytes.length s in
Line 1,707: Line 1,707:
done;
done;
(Bytes.to_string res)
(Bytes.to_string res)
;;</lang>
;;</syntaxhighlight>
which gives the signature<lang ocaml>val string_repeat : string -> int -> string = <fun></lang>
which gives the signature<syntaxhighlight lang="ocaml">val string_repeat : string -> int -> string = <fun></syntaxhighlight>


testing in the toplevel:
testing in the toplevel:
<lang ocaml># string_repeat "Hiuoa" 3 ;;
<syntaxhighlight lang="ocaml"># string_repeat "Hiuoa" 3 ;;
- : string = "HiuoaHiuoaHiuoa"</lang>
- : string = "HiuoaHiuoaHiuoa"</syntaxhighlight>


Alternately create an array initialized to s, and concat:
Alternately create an array initialized to s, and concat:
<lang ocaml>let string_repeat s n =
<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))
;;</lang>
;;</syntaxhighlight>


Or:
Or:
<lang ocaml>let string_repeat s n =
<syntaxhighlight lang="ocaml">let string_repeat s n =
Array.fold_left (^) "" (Array.make n s)
Array.fold_left (^) "" (Array.make n s)
;;</lang>
;;</syntaxhighlight>


To repeat a single character use:
To repeat a single character use:
<lang ocaml>String.make 5 '*'</lang>
<syntaxhighlight lang="ocaml">String.make 5 '*'</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth>StringBuffer new "abcd" <<n(5)</lang>
<syntaxhighlight lang="oforth">StringBuffer new "abcd" <<n(5)</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang Progress (OpenEdge ABL)>MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.</lang>
<syntaxhighlight lang="progress (openedge abl)">MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.</syntaxhighlight>


=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">


'REPEATING A CHARACTER
'REPEATING A CHARACTER
Line 1,754: Line 1,754:


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:
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {Repeat Xs N}
fun {Repeat Xs N}
if N > 0 then
if N > 0 then
Line 1,767: Line 1,767:
end
end
in
in
{System.showInfo {Repeat "Ha" 5}}</lang>
{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.
<lang parigp>repeat(s,n)={
<syntaxhighlight lang="parigp">repeat(s,n)={
if(n, Str(repeat(s, n-1), s), "")
if(n, Str(repeat(s, n-1), s), "")
};</lang>
};</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.
<lang parigp>repeat(s,n)=concat(vector(n,i, s));</lang>
<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.
<lang parigp>repeat(s,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,787: Line 1,787:
repeat(Str(s,s),n\2)
repeat(Str(s,s),n\2)
);
);
}</lang>
}</syntaxhighlight>


===Version #2. Simple loop based.===
===Version #2. Simple loop based.===
Line 1,795: Line 1,795:
for the heavy text processing.
for the heavy text processing.


<lang parigp>
<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,816: Line 1,816:
print1("6."); for(i=1,10000000, srepeat("e",10));
print1("6."); for(i=1,10000000, srepeat("e",10));
}
}
</lang>
</syntaxhighlight>


{{Output}}
{{Output}}
Line 1,835: Line 1,835:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>"ha" x 5</lang>
<syntaxhighlight lang="perl">"ha" x 5</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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>
<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>
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,849: Line 1,849:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>def rep /# s n -- s #/
<syntaxhighlight lang="phixmonti">def rep /# s n -- s #/
"" swap
"" swap
for drop
for drop
Line 1,857: Line 1,857:
enddef
enddef


"ha" 5 rep print</lang>
"ha" 5 rep print</syntaxhighlight>
Same result (simple character):
Same result (simple character):
<lang Phixmonti>65 5 rep
<syntaxhighlight lang="phixmonti">65 5 rep
65 5 repeat
65 5 repeat
'A' 5 repeat</lang>
'A' 5 repeat</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>str_repeat("ha", 5)</lang>
<syntaxhighlight lang="php">str_repeat("ha", 5)</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(pack (need 5 "ha"))
<syntaxhighlight lang="picolisp">(pack (need 5 "ha"))
-> "hahahahaha"</lang>
-> "hahahahaha"</syntaxhighlight>
or:
or:
<lang PicoLisp>(pack (make (do 5 (link "ha"))))
<syntaxhighlight lang="picolisp">(pack (make (do 5 (link "ha"))))
-> "hahahahaha"</lang>
-> "hahahahaha"</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>"ha"*5;</lang>
<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,889: Line 1,889:


s = (5)'h'; /* asigns 'hhhhh' to s. */
s = (5)'h'; /* asigns 'hhhhh' to s. */
</syntaxhighlight>
</lang>


=={{header|Plain English}}==
=={{header|Plain English}}==
<lang plainenglish>To run:
<syntaxhighlight lang="plainenglish">To run:
Start up.
Start up.
Put "ha" into a string.
Put "ha" into a string.
Line 1,907: Line 1,907:
Privatize the number.
Privatize the number.
Subtract 1 from the number.
Subtract 1 from the number.
Append the string to the original string given the number.</lang>
Append the string to the original string given the number.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,915: Line 1,915:


=={{header|Plorth}}==
=={{header|Plorth}}==
<lang plorth>"ha" 5 *</lang>
<syntaxhighlight lang="plorth">"ha" 5 *</syntaxhighlight>


=={{header|PostScript}}==
=={{header|PostScript}}==
<lang PostScript>% the comments show the stack content after the line was executed
<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,936: Line 1,936:
} for
} for
pop % fstring
pop % fstring
} def</lang>
} def</syntaxhighlight>


=={{header|PowerBASIC}}==
=={{header|PowerBASIC}}==
<lang powerbasic>MSGBOX REPEAT$(5, "ha")</lang>
<syntaxhighlight lang="powerbasic">MSGBOX REPEAT$(5, "ha")</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>"ha" * 5 # ==> "hahahahaha"</lang>
<syntaxhighlight lang="powershell">"ha" * 5 # ==> "hahahahaha"</syntaxhighlight>


=={{header|Processing}}==
=={{header|Processing}}==
<lang processing>void setup() {
<syntaxhighlight lang="processing">void setup() {
String rep = repeat("ha", 5);
String rep = repeat("ha", 5);
println(rep);
println(rep);
Line 1,954: Line 1,954:
// 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);
}</lang>
}</syntaxhighlight>


==={{header|Processing Python mode}}===
==={{header|Processing Python mode}}===
<lang python>def setup():
<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</lang>
return s * times</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
<lang prolog>%repeat(Str,Num,Res).
<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).</lang>
string_concat(Str, Res1, Res).</syntaxhighlight>


=== alternative using DCG strings ===
=== alternative using DCG strings ===
Line 1,979: Line 1,979:
{{works with|SWI-Prolog|7}}
{{works with|SWI-Prolog|7}}


<lang prolog>
<syntaxhighlight lang="prolog">
:- system:set_prolog_flag(double_quotes,chars) .
:- system:set_prolog_flag(double_quotes,chars) .


Line 2,002: Line 2,002:
.
.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,056: Line 2,056:
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.


<lang pure>> str_repeat 0 s = "";
<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"
></lang>
></syntaxhighlight>


You can define str_repeat using infinite lazy list (stream).
You can define str_repeat using infinite lazy list (stream).


<lang pure>
<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}}==
<lang PureBasic>Procedure.s RepeatString(count, text$=" ")
<syntaxhighlight lang="purebasic">Procedure.s RepeatString(count, text$=" ")
Protected i, ret$=""
Protected i, ret$=""


Line 2,078: Line 2,078:
EndProcedure
EndProcedure


Debug RepeatString(5, "ha")</lang>
Debug RepeatString(5, "ha")</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>"ha" * 5 # ==> "hahahahaha"</lang>
<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:
<lang python>5 * "ha" # ==> "hahahahaha"</lang>
<syntaxhighlight lang="python">5 * "ha" # ==> "hahahahaha"</syntaxhighlight>


=== Using a Function ===
=== Using a Function ===
<lang python>def repeat(s, times):
<syntaxhighlight lang="python">def repeat(s, times):
return s * times
return s * times


print(repeat("ha", 5))</lang>
print(repeat("ha", 5))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>


=== Using Lambda ===
=== Using Lambda ===
<lang python>x = lambda a: a * 5
<syntaxhighlight lang="python">x = lambda a: a * 5
print(x("ha"))</lang>
print(x("ha"))</syntaxhighlight>
{{Out}}
{{Out}}
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang Quackery>$ "ha" 5 of echo$</lang>
<syntaxhighlight lang="quackery">$ "ha" 5 of echo$</syntaxhighlight>
'''Output:'''
'''Output:'''
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>


=={{header|R}}==
=={{header|R}}==
<lang ruby>strrep("ha", 5)</lang>
<syntaxhighlight lang="ruby">strrep("ha", 5)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
;; fast
;; fast
Line 2,116: Line 2,116:
(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:
<lang racket>
<syntaxhighlight lang="racket">
(make-string 5 #\*) => "*****"
(make-string 5 #\*) => "*****"
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>print "ha" x 5</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 2,142: Line 2,142:


showmessage Repeat$("ha", 5)
showmessage Repeat$("ha", 5)
</syntaxhighlight>
</lang>


=={{header|REALbasic}}==
=={{header|REALbasic}}==
<lang vb>Function Repeat(s As String, count As Integer) As String
<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 2,152: Line 2,152:
Return output
Return output
End Function
End Function
</syntaxhighlight>
</lang>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>head insert/dup "" "ha" 5</lang>
<syntaxhighlight lang="rebol">head insert/dup "" "ha" 5</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>>> str: "Add duplicates to string"
<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"</lang>
== "hahahaAdd duplicates to stringhahaha"</syntaxhighlight>


=={{header|ReScript}}==
=={{header|ReScript}}==
<lang ReScript>Js.log(Js.String2.repeat("ha", 5))</lang>
<syntaxhighlight lang="rescript">Js.log(Js.String2.repeat("ha", 5))</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>with strings'
<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</lang>
"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.
<lang REXX>/*REXX program to show various ways to repeat a string (or repeat a single char).*/
<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 2,293: Line 2,293:
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.*/</lang>
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}}==
<lang ring> Copy("ha" , 5) # ==> "hahahahaha"</lang>
<syntaxhighlight lang="ring"> Copy("ha" , 5) # ==> "hahahahaha"</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>"ha" * 5 # ==> "hahahahaha"</lang>
<syntaxhighlight lang="ruby">"ha" * 5 # ==> "hahahahaha"</syntaxhighlight>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>a$ = "ha "
<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$</lang>
print a$</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>std::iter::repeat("ha").take(5).collect::<String>(); // ==> "hahahahaha"</lang>
<syntaxhighlight lang="rust">std::iter::repeat("ha").take(5).collect::<String>(); // ==> "hahahahaha"</syntaxhighlight>


Since 1.16:
Since 1.16:
<lang rust>"ha".repeat(5); // ==> "hahahahaha"</lang>
<syntaxhighlight lang="rust">"ha".repeat(5); // ==> "hahahahaha"</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>"ha" * 5 // ==> "hahahahaha"</lang>
<syntaxhighlight lang="scala">"ha" * 5 // ==> "hahahahaha"</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (string-repeat n str)
<syntaxhighlight lang="scheme">(define (string-repeat n str)
(apply string-append (vector->list (make-vector n str))))</lang>
(apply string-append (vector->list (make-vector n str))))</syntaxhighlight>
with SRFI 1:
with SRFI 1:
<lang scheme>(define (string-repeat n str)
<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"</lang>
(string-repeat 5 "ha") ==> "hahahahaha"</syntaxhighlight>


To repeat a single character:
To repeat a single character:
<lang scheme>(make-string 5 #\*)</lang>
<syntaxhighlight lang="scheme">(make-string 5 #\*)</syntaxhighlight>


=={{header|Scratch}}==
=={{header|Scratch}}==
Line 2,338: Line 2,338:
=={{header|sed}}==
=={{header|sed}}==
Number of ampersands indicates number of repetitions.
Number of ampersands indicates number of repetitions.
<lang sed>
<syntaxhighlight lang="sed">
$ echo ha | sed 's/.*/&&&&&/'
$ echo ha | sed 's/.*/&&&&&/'
hahahahaha
hahahahaha
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<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;</lang>
end func;</syntaxhighlight>


Output:
Output:
Line 2,357: Line 2,357:


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang 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 2,369: Line 2,369:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>'ha' * 5; # ==> 'hahahahaha'</lang>
<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.
<lang basic> 10 LET S$="HA"
<syntaxhighlight lang="basic"> 10 LET S$="HA"
20 LET N=5
20 LET N=5
30 GOSUB 60
30 GOSUB 60
Line 2,382: Line 2,382:
80 LET T$=T$+S$
80 LET T$=T$+S$
90 NEXT I
90 NEXT I
100 RETURN</lang>
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::
<lang smalltalk>v := 'ha'.
<syntaxhighlight lang="smalltalk">v := 'ha'.
v,v,v,v,v</lang>
v,v,v,v,v</syntaxhighlight>


{{works with|Pharo|1.4}}
{{works with|Pharo|1.4}}
Line 2,395: Line 2,395:
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:


<lang smalltalk>((1 to: n) collect: [:x | 'ha']) joinUsing: ''.</lang>
<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}}


<lang smalltalk>(Array new:n withAll:'ha') asStringWith:''.</lang>
<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:


<lang smalltalk>ws := '' writeStream.
<syntaxhighlight lang="smalltalk">ws := '' writeStream.
n timesRepeat: [ws nextPutAll: 'ha'].
n timesRepeat: [ws nextPutAll: 'ha'].
ws contents.</lang>
ws contents.</syntaxhighlight>
alternatively:
alternatively:
<lang smalltalk>(String streamContents:[:ws | n timesRepeat: [ws nextPutAll: 'ha']])</lang>
<syntaxhighlight lang="smalltalk">(String streamContents:[:ws | n timesRepeat: [ws nextPutAll: 'ha']])</syntaxhighlight>


all evaluate to:
all evaluate to:
Line 2,414: Line 2,414:


A string containing a repeated character is generated with:
A string containing a repeated character is generated with:
<lang smalltalk>String new:n withAll:$*</lang>
<syntaxhighlight lang="smalltalk">String new:n withAll:$*</syntaxhighlight>


{{works with|VA Smalltalk}}
{{works with|VA Smalltalk}}
<lang smalltalk>(String new:n) atAllPut:$*</lang>
<syntaxhighlight lang="smalltalk">(String new:n) atAllPut:$*</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang snobol4> output = dupl("ha",5)
<syntaxhighlight lang="snobol4"> output = dupl("ha",5)
end</lang>
end</syntaxhighlight>


=={{header|Sparkling}}==
=={{header|Sparkling}}==
<lang sparkling>spn:3> repeat("na", 8) .. " Batman!"
<syntaxhighlight lang="sparkling">spn:3> repeat("na", 8) .. " Batman!"
= nananananananana Batman!</lang>
= nananananananana Batman!</syntaxhighlight>


=={{header|SQL}}==
=={{header|SQL}}==
<lang sql>select rpad('', 10, 'ha')</lang>
<syntaxhighlight lang="sql">select rpad('', 10, 'ha')</syntaxhighlight>


=={{header|SQL PL}}==
=={{header|SQL PL}}==
{{works with|Db2 LUW}}
{{works with|Db2 LUW}}
<lang sql pl>
<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,457: Line 2,457:


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun string_repeat (s, n) =
<syntaxhighlight lang="sml">fun string_repeat (s, n) =
concat (List.tabulate (n, fn _ => s))
concat (List.tabulate (n, fn _ => s))
;</lang>
;</syntaxhighlight>


testing in the interpreter:
testing in the interpreter:
<lang sml>- string_repeat ("Hiuoa", 3) ;
<syntaxhighlight lang="sml">- string_repeat ("Hiuoa", 3) ;
val it = "HiuoaHiuoaHiuoa" : string</lang>
val it = "HiuoaHiuoaHiuoa" : string</syntaxhighlight>


To repeat a single character:
To repeat a single character:
<lang sml>fun char_repeat (c, n) =
<syntaxhighlight lang="sml">fun char_repeat (c, n) =
implode (List.tabulate (n, fn _ => c))
implode (List.tabulate (n, fn _ => c))
;</lang>
;</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
<lang stata>. scalar a="ha"
<syntaxhighlight lang="stata">. scalar a="ha"
. scalar b=a*5
. scalar b=a*5
. display b
. display b
hahahahaha</lang>
hahahahaha</syntaxhighlight>


=={{header|Suneido}}==
=={{header|Suneido}}==
<lang Suneido>'ha'.Repeat(5) --> "hahahahaha"
<syntaxhighlight lang="suneido">'ha'.Repeat(5) --> "hahahahaha"
'*'.Repeat(5) --> "*****"</lang>
'*'.Repeat(5) --> "*****"</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
Line 2,484: Line 2,484:
=== The Builtin Way ===
=== The Builtin Way ===


<lang swift>print(String(repeating:"*", count: 5))</lang>
<syntaxhighlight lang="swift">print(String(repeating:"*", count: 5))</syntaxhighlight>
{{out}}*****
{{out}}*****


=== Functions ===
=== Functions ===


<lang swift>func * (left:String, right:Int) -> String {
<syntaxhighlight lang="swift">func * (left:String, right:Int) -> String {
return String(repeating:left, count:right)
return String(repeating:left, count:right)
}
}


print ("HA" * 5)
print ("HA" * 5)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
HAHAHAHAHA
HAHAHAHAHA
Line 2,502: Line 2,502:
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.


<lang swift>extension String {
<syntaxhighlight lang="swift">extension String {
// Slower version
// Slower version
func repeatString(n: Int) -> String {
func repeatString(n: Int) -> String {
Line 2,520: Line 2,520:


print( "ha".repeatString(5) )
print( "ha".repeatString(5) )
print( "he".repeatString2(5) )</lang>
print( "he".repeatString2(5) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,528: Line 2,528:


To repeat a single character:
To repeat a single character:
<lang swift>String(count:5, repeatedValue:"*" as 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,536: Line 2,536:
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.


<lang swift>extension String {
<syntaxhighlight lang="swift">extension String {
func repeatBiterative(count: Int) -> String {
func repeatBiterative(count: Int) -> String {
var reduceCount = count
var reduceCount = count
Line 2,554: Line 2,554:
}
}


"He".repeatBiterative(5)</lang>
"He".repeatBiterative(5)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,561: Line 2,561:


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang 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}}==
<lang tcl>string repeat "ha" 5 ;# => hahahahaha</lang>
<syntaxhighlight lang="tcl">string repeat "ha" 5 ;# => hahahahaha</syntaxhighlight>


=={{header|TorqueScript}}==
=={{header|TorqueScript}}==
--[[User:Eepos|Eepos]]
--[[User:Eepos|Eepos]]
<lang TorqueScript>function strRep(%str,%int)
<syntaxhighlight lang="torquescript">function strRep(%str,%int)
{
{
for(%i = 0; %i < %int; %i++)
for(%i = 0; %i < %int; %i++)
Line 2,580: Line 2,580:


return %rstr;
return %rstr;
}</lang>
}</syntaxhighlight>


=={{header|Tosh}}==
=={{header|Tosh}}==
<lang Tosh>when flag clicked
<syntaxhighlight lang="tosh">when flag clicked
set String to "meow"
set String to "meow"
set Count to 4
set Count to 4
Line 2,590: Line 2,590:
set Repeated to (join (Repeated) (String))
set Repeated to (join (Repeated) (String))
end
end
stop this script</lang>
stop this script</syntaxhighlight>


=={{header|Transact-SQL}}==
=={{header|Transact-SQL}}==
<lang tsql>select REPLICATE( 'ha', 5 )</lang>
<syntaxhighlight lang="tsql">select REPLICATE( 'ha', 5 )</syntaxhighlight>


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang 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,606: Line 2,606:
{{works with|ksh93}}
{{works with|ksh93}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>printf "ha"%.0s {1..5}</lang>
<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,612: Line 2,612:
{{works with|ksh93}}
{{works with|ksh93}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>i=5
<syntaxhighlight lang="bash">i=5
printf "ha"%.0s {1..$i}</lang>
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,620: Line 2,620:
{{works with|ksh93}}
{{works with|ksh93}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>i=5
<syntaxhighlight lang="bash">i=5
eval "printf 'ha'%.0s {1..$i}"</lang>
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,628: Line 2,628:
{{works with|ksh93}}
{{works with|ksh93}}
{{works with|zsh}}
{{works with|zsh}}
<lang bash>reprint() {
<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</lang>
reprint '% ha \' 5</syntaxhighlight>


=== Using repeat ===
=== Using repeat ===
Line 2,638: Line 2,638:
{{works with|csh}}
{{works with|csh}}


<lang bash>
<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,648: Line 2,648:
{{works with|Bourne Shell}}
{{works with|Bourne Shell}}


<lang sh>width=72; char='='
<syntaxhighlight lang="sh">width=72; char='='
head -c ${width} < /dev/zero | tr '\0' "$char"</lang>
head -c ${width} < /dev/zero | tr '\0' "$char"</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import nat
<syntaxhighlight lang="ursala">#import nat


repeat = ^|DlSL/~& iota
repeat = ^|DlSL/~& iota
Line 2,658: Line 2,658:
#cast %s
#cast %s


example = repeat('ha',5)</lang>
example = repeat('ha',5)</syntaxhighlight>
output:
output:
<pre>'hahahahaha'</pre>
<pre>'hahahahaha'</pre>
Line 2,664: Line 2,664:
=={{header|Vala}}==
=={{header|Vala}}==
Repeat a string 5 times:
Repeat a string 5 times:
<lang vala>
<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:
<lang vala>
<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>
<lang VBA>Public Function RepeatStr(aString As String, aNumber As Integer) As String
<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,687: Line 2,687:
End Function
End Function


Debug.Print RepeatStr("ha", 5)</lang>
Debug.Print RepeatStr("ha", 5)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,694: Line 2,694:
''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:
<lang vba>Public Function RepeatString(stText As String, iQty As Integer) As String
<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</lang>
End Function</syntaxhighlight>
<br>'''Repeat a character'''<br>
<br>'''Repeat a character'''<br>
<lang VBA>Debug.Print String(5, "x")</lang>
<syntaxhighlight lang="vba">Debug.Print String(5, "x")</syntaxhighlight>
{{out}}
{{out}}
<pre>xxxxx</pre>
<pre>xxxxx</pre>
Line 2,704: Line 2,704:
=={{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,712: Line 2,712:
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}}==
<lang vedit>Ins_Text("ha", COUNT, 5) </lang>
<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>
<lang vb>Public Function StrRepeat(s As String, n As Integer) As String
<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,729: Line 2,729:
End Function
End Function
Debug.Print StrRepeat("ha", 5)</lang>
Debug.Print StrRepeat("ha", 5)</syntaxhighlight>
{{out}}
{{out}}
<pre>hahahahaha</pre>
<pre>hahahahaha</pre>


An alternative method:
An alternative method:
<lang vb>Public Function StrRepeat(sText As String, n As Integer) As String
<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</lang>
End Function</syntaxhighlight>


<br>'''Repeat a character'''<br>
<br>'''Repeat a character'''<br>
<lang VBA>Debug.Print String(5, "x")</lang>
<syntaxhighlight lang="vba">Debug.Print String(5, "x")</syntaxhighlight>
{{out}}
{{out}}
<pre>xxxxx</pre>
<pre>xxxxx</pre>
Line 2,745: Line 2,745:
=={{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,754: Line 2,754:


<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,768: Line 2,768:
=={{header|Visual FoxPro}}==
=={{header|Visual FoxPro}}==
Use the built in function REPLICATE(string, number):
Use the built in function REPLICATE(string, number):
<lang vfp>? REPLICATE("HO", 3)</lang>
<syntaxhighlight lang="vfp">? REPLICATE("HO", 3)</syntaxhighlight>


produces
produces
Line 2,774: Line 2,774:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang go>// Repeat a string, in V
<syntaxhighlight lang="go">// Repeat a string, in V
// Tectonics: v run repeat-a-string.v
// Tectonics: v run repeat-a-string.v
module main
module main
Line 2,787: Line 2,787:
// This indexes the string to get the first byte of the rune array
// This indexes the string to get the first byte of the rune array
println(strings.repeat("*"[0], 5))
println(strings.repeat("*"[0], 5))
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>prompt$ v run rosetta/repeat-a-string.v
<pre>prompt$ v run rosetta/repeat-a-string.v
Line 2,794: Line 2,794:


=={{header|Wart}}==
=={{header|Wart}}==
<lang wart>def (s * n) :case (string? s)
<syntaxhighlight lang="wart">def (s * n) :case (string? s)
with outstring
with outstring
repeat n
repeat n
Line 2,800: Line 2,800:


("ha" * 5)
("ha" * 5)
=> "hahahahaha"</lang>
=> "hahahahaha"</syntaxhighlight>


=={{header|Wortel}}==
=={{header|Wortel}}==
<lang wortel>@join "" @rep 5 "ha" ; returns "hahahahaha"</lang>
<syntaxhighlight lang="wortel">@join "" @rep 5 "ha" ; returns "hahahahaha"</syntaxhighlight>
As a function:
As a function:
<lang wortel>^(\@join "" @rep)</lang>
<syntaxhighlight lang="wortel">^(\@join "" @rep)</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>System.print("ha" * 5)</lang>
<syntaxhighlight lang="ecmascript">System.print("ha" * 5)</syntaxhighlight>


{{out}}
{{out}}
Line 2,816: Line 2,816:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>cod T=12; int I; for I gets 1,5 do T(0,"ha")</lang>
<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}}==
<lang yorick>array("ha", 5)(sum)</lang>
<syntaxhighlight lang="yorick">array("ha", 5)(sum)</syntaxhighlight>


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
<lang z80>PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints the ascii code in the accumulator to the screen.
<syntaxhighlight lang="z80">PrintChar equ &BB5A ;Amstrad CPC BIOS call, prints the ascii code in the accumulator to the screen.


org &8000
org &8000
Line 2,848: Line 2,848:
call PrintChar ; BIOS call, all regs are preserved.
call PrintChar ; BIOS call, all regs are preserved.
inc hl ; next char
inc hl ; next char
jr PrintString ; back to start.</lang>
jr PrintString ; back to start.</syntaxhighlight>


{{out}}
{{out}}
Line 2,857: Line 2,857:
=={{header|zig}}==
=={{header|zig}}==
At compile-time:
At compile-time:
<lang zig>const laugh = "ha" ** 5;</lang>
<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.
<lang zig>const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");
const warn = std.debug.warn;
const warn = std.debug.warn;


Line 2,879: Line 2,879:
const ex = try repeat("ha", 5, allocator);
const ex = try repeat("ha", 5, allocator);
defer allocator.free(ex);
defer allocator.free(ex);
}</lang>
}</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Same as [[#Ruby|Ruby]]
Same as [[#Ruby|Ruby]]
<lang zkl>"ha" * 5 # --> "hahahahaha"</lang>
<syntaxhighlight lang="zkl">"ha" * 5 # --> "hahahahaha"</syntaxhighlight>