Repeat a string: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 145: Line 145:
);</lang>
);</lang>


repeat$(ha.5)
<pre> repeat$(ha.5)
hahahahaha
hahahahaha</pre>


=={{header|Brat}}==
=={{header|Brat}}==

Revision as of 20:51, 4 March 2012

Task
Repeat a string
You are encouraged to solve this task according to the task description, using any language you may know.

Take a string and repeat it some number of times. Example: repeat("ha", 5) => "hahahahaha"

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

4DOS Batch

<lang 4dos>gosub repeat ha 5 echo %@repeat[*,5] quit

Repeat [String Times]
   do %Times%
       echos %String%
   enddo
   echo.

return</lang> Output shows:

hahahahaha
*****

ActionScript

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

In Flex, there is the method mx.utils.StringUtil.repeat().

Iterative version

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

Recursive version

The following double-and-add method is much faster when repeating a string many times. <lang ActionScript>function repeatRecursive(string:String, numTimes:uint):String { if(numTimes == 0) return ""; if(numTimes & 1) return string + repeatRecursive(string, numTimes - 1); var tmp:String = repeatRecursive(string, numTimes/2); return tmp + tmp; }</lang>

Flex

<lang ActionScript>import mx.utils.StringUtil; trace(StringUtil.repeat("ha", 5)); </lang> Sample Output:

hahahahaha

Ada

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; with Ada.Text_IO; use Ada.Text_IO;

procedure String_Multiplication is begin

  Put_Line (5 * "ha");

end String_Multiplication;</lang> Sample output:

hahahahaha

ALGOL 68

<lang algol68>print (5 * "ha") </lang>


AppleScript

<lang AppleScript>set str to "ha" set final_string to "" repeat 5 times

    set final_string to final_string & str

end repeat</lang>


AutoHotkey

<lang AutoHotkey>MsgBox % Repeat("ha",5)

Repeat(String,Times) {

 Loop, %Times%
   Output .= String
 Return Output

}</lang>

AWK

<lang awk>function repeat( str, n, rep, i ) {

   for( ; i<n; i++ )
       rep = rep str   
   return rep

}

BEGIN {

   print repeat( "ha", 5 )

}</lang>

Batch File

Commandline implementation <lang dos>@echo off if "%2" equ "" goto fail setlocal enabledelayedexpansion set char=%1 set num=%2 for /l %%i in (1,1,%num%) do set res=!res!%char% echo %res%

fail</lang>

'Function' version <lang dos>@echo off set /p a=Enter string to repeat : set /p b=Enter how many times to repeat : set "c=1" set "d=%b%"

a

echo %a% set "c=%c%+=1" if /i _"%c%"==_"%d%" (exit /b) goto :a</lang>

BBC BASIC

<lang bbcbasic> PRINT STRING$(5, "ha")</lang>

Brainf***

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 [-> +++++ +++++<] we add 10 to second each loopround

Now we want to loop 5 times to follow std +++++ [-> ++++ . ----- -- . +++<] print h and a each loop

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

Bracmat

The code almost explains itself. The repetions are accumulated in a list rep. The str concatenates all elements into a single string, ignoring the white spaces separating the elements.

<lang bracmat>(repeat=

 string N rep

. !arg:(?string.?N)

 & !string:?rep
 &   whl
   ' (!N+-1:>0:?N&!string !rep:?rep)
 & str$!rep

);</lang>

 repeat$(ha.5)
 hahahahaha

Brat

<lang brat>p "ha" * 5 #Prints "hahahahaha"</lang>

C

<lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>

char * string_repeat( int n, const char * s ) {

 size_t slen = strlen(s);
 char * dest = malloc(n*slen+1);
 int i; char * p;
 for ( i=0, p = dest; i < n; ++i, p += slen ) {
   memcpy(p, s, slen);
 }
 *p = '\0';
 return dest;

}

int main() {

 char * result = string_repeat(5, "ha")
 puts(result);
 free(result);
 return 0;

}</lang> A variation. <lang c>... char *string_repeat(char *str, int n) {

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

}</lang>

To repeat a single character <lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>

char * char_repeat( int n, char c ) {

 char * dest = malloc(n+1);
 memset(dest, c, n);
 dest[n] = '\0';
 return dest;

}

int main() {

 char * result = char_repeat(5, '*');
 puts(result);
 free(result);
 return 0;

}</lang>

C#

<lang csharp>string s = "".PadLeft(5, 'X').Replace("X", "ha");</lang> or (with .NET 2+) <lang csharp>string s = new String('X', 5).Replace("X", "ha");</lang> or (with .NET 2+) <lang csharp>string s = String.Join("ha", new string[5 + 1]);</lang> or (with .NET 4+) <lang csharp>string s = String.Concat(Enumerable.Repeat("ha", 5));</lang>

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

C++

<lang cpp>#include <string>

  1. include <iostream>

std::string repeat( const std::string &word, int times ) {

  std::string result ;
  result.reserve(times*word.length()); // avoid repeated reallocation
  for ( int a = 0 ; a < times ; a++ ) 
     result += word ;
  return result ;

}

int main( ) {

  std::cout << repeat( "Ha" , 5 ) << std::endl ;
  return 0 ;

}</lang>

To repeat a single character: <lang cpp>#include <string>

  1. include <iostream>

int main( ) {

  std::cout << std::string( 5, '*' ) << std::endl ;
  return 0 ;

}</lang>

Clojure

<lang lisp>(apply str (repeat 5 "ha"))</lang>

Common Lisp

<lang lisp>(defun repeat-string (n string)

 (with-output-to-string (stream)
   (loop repeat n do (write-string string stream))))

(princ (repeat-string 5 "hi"))</lang>

A single character may be repeated using just the builtin make-string: <lang lisp>(make-string 5 :initial-element #\X)</lang> produces “XXXXX”.

D

Repeating a string: <lang d>import std.stdio, std.string;

void main() {

   writefln("ha".repeat(5));

}</lang> Repeating a character with vector operations: <lang d>import std.stdio;

void main() {

   char[] chars;     // create the dynamic array
   chars.length = 5; // set the length
   chars[] = '*';    // set all characters in the string to '*'
   writefln(chars);

}</lang>


Delphi

Repeat a string <lang Delphi> function RepeatString(const s: string; count: cardinal): string; var

 i: Integer;

begin

 for i := 1 to count do
   Result := Result + s;

end;

Writeln(RepeatString('ha',5)); </lang>

Repeat a character

<lang Delphi> Writeln( StringOfChar('a',5) ); </lang>


Built in RTL function:

<lang Delphi>StrUtils.DupeString</lang>

DWScript

Repeat a string

<lang Delphi> PrintLn( StringOfString('abc',5) ); </lang>

Repeat a character

<lang Delphi> PrintLn( StringOfChar('a',5) ); </lang>

E

<lang e>"ha" * 5</lang>

Erlang

<lang erlang>repeat(X,N) ->

   lists:flatten(lists:duplicate(N,X)).</lang>

This will duplicate a string or character N times to produce a new string.

Euphoria

<lang Euphoria>function repeat_string(object x, integer times)

   sequence out
   if atom(x) then
       return repeat(x,times)
   else
       out = ""
       for n = 1 to times do
           out &= x
       end for
       return out
   end if

end function

puts(1,repeat_string("ha",5) & '\n') -- hahahahaha

puts(1,repeat_string('*',5) & '\n') -- *****</lang> Sample Output:

hahahahaha
*****

<lang Euphoria>-- Here is an alternative method for "Repeat a string" include std/sequence.e printf(1,"Here is the repeated string: %s\n", {repeat_pattern("ha",5)}) printf(1,"Here is another: %s\n", {repeat_pattern("*",5)}) </lang> Sample Output:

Here is the repeated string: hahahahaha
Here is another: *****

F#

<lang fsharp>> String.replicate 5 "ha";; val it : string = "hahahahaha"</lang> Or <lang fsharp>> String.Concat( Array.create 5 "ha" );; val it : string = "hahahahaha"</lang>

Factor

<lang factor>: repeat-string ( str n -- str' ) swap <repetition> concat ;

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

Forth

<lang forth>: place-n { src len dest n -- }

 0 dest c!
 n 0 ?do src len dest +place loop ;

s" ha" pad 5 place-n pad count type \ hahahahaha</lang> The same code without the use of locals: <lang forth>

place-n ( src len dest n -- )
 swap >r 0 r@ c!
 begin dup while -rot 2dup r@ +place rot 1- repeat
 r> 2drop 2drop ;

s" ha" pad 5 place-n pad count type \ hahahahaha</lang> Filling a string with a single character is supported by ANS-Forth: <lang forth>pad 10 char * fill \ repeat a single character pad 10 type \ **********</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>program test_repeat

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

end program test_repeat</lang> Output:

hahahahaha

Frink

<lang frink> println[repeat["ha", 5]] </lang>

GAP

<lang gap>Concatenation(List([1 .. 10], n -> "BOB "));

  1. "BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB "</lang>

Go

<lang go>fmt.Println(strings.Repeat("ha", 5)) // ==> "hahahahaha"</lang> 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>

Groovy

<lang groovy> println 'ha' * 5</lang>

Haskell

For a string of finite length: <lang haskell>concat $ replicate 5 "ha"</lang>

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

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

To repeat a single character: <lang haskell>replicate 5 '*'</lang>

HicEst

<lang HicEst>CHARACTER out*20

EDIT(Text=out, Insert="ha", DO=5)</lang>

Icon and Unicon

The procedure repl is a supplied function in Icon and Unicon. <lang Icon>procedure main(args)

   write(repl(integer(!args) | 5))

end</lang> If it weren't, one way to write it is: <lang Icon>procedure repl(s, n)

   every (ns := "") ||:= |s\(0 <= n)
   return ns

end</lang>

Inform 7

<lang inform7>Home is a room.

To decide which indexed text is (T - indexed text) repeated (N - number) times: let temp be indexed text; repeat with M running from 1 to N: let temp be "[temp][T]"; decide on temp.

When play begins: say "ha" repeated 5 times; end the story.</lang>

J

<lang j> 5 # '*' NB. repeat each item 5 times

  5 # 'ha'              NB. repeat each item 5 times

hhhhhaaaaa

  (5 * # 'ha') $ 'ha'   NB. repeat array 5 times (explicit)

hahahahaha

  5 ((* #) $ ]) 'ha'    NB. repeat array 5 times (tacit)

hahahahaha</lang>

Java

Works with: Java version 1.5+

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){

  StringBuilder ret = new StringBuilder();
  for(int i = 0;i < times;i++) ret.append(str);
  return ret.toString();

}

public static void main(String[] args){

 System.out.println(repeat("ha", 5));

}</lang>

Or even shorter: <lang java5>public static String repeat(String str, int times){

  return new String(new char[times]).replace("\0", str);

}</lang>

In Apache Commons Lang, there is a StringUtils.repeat() method.

JavaScript

This solution creates an empty array of length n+1, then uses the array's join method to effectively concatenate the string n times. Note that extending the prototype of built-in objects is not a good idea if the code is to run in a shared workspace. <lang javascript>String.prototype.repeat = function(n) {

   return new Array(1 + n).join(this);

}

alert("ha".repeat(5)); // hahahahaha</lang>

K

<lang k>

 ,/5#,"ha"

"hahahahaha"

 5#"*"

"*****" </lang>

LabVIEW

I don't know if there is a built-in function for this, but it is easily achieved with a For loop and Concatenate Strings.

Liberty BASIC

<lang lb>a$ ="ha " print StringRepeat$( a$, 5)

end

function StringRepeat$( in$, n)

   o$ =""
   for i =1 to n
       o$ =o$ +in$
   next i
   StringRepeat$ =o$

end function</lang>

<lang logo>to copies :n :thing [:acc "||]

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

end</lang> or using cascade: <lang logo>show cascade 5 [combine "ha ?] "||  ; hahahahaha</lang>

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

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

end

print copies 5 "ha "||</lang>

Lua

<lang lua>function repeats(s, n) return n > 0 and s .. repeat(s, n-1) or "" end</lang>

Or use native string library function <lang lua>string.rep(s,n)</lang>

Mathematica

<lang Mathematica>Apply[StringJoin,ConstantArray["HA",{100}]]</lang>


MATLAB / Octave

<lang MATLAB>function S = repeat(s , n)

   S = repmat(s , [1,n]) ;

return</lang>

Note 1: The repetition is returned, not displayed.
Note 2: To repeat a string, use single quotes. Example: S=repeat('ha',5)

Mercury

Mercury's 'string' module provides an efficient char-repeater. The following uses string.builder to repeat strings.

<lang Mercury>:- module repeat.

- interface.
- import_module string, char, int.
- func repeat_char(char, int) = string.
- func repeat(string, int) = string.
- implementation.
- import_module stream, stream.string_writer, string.builder.

repeat_char(C, N) = string.duplicate_char(C, N).

repeat(String, Count) = Repeated :-

       S0 = string.builder.init,
       Repeated = string.builder.to_string(S),
       printn(string.builder.handle, Count, String, S0, S).
- pred printn(Stream, int, string, State, State)
              <= (stream.writer(Stream, string, State),
                  stream.writer(Stream, character, State)).
- mode printn(in, in, in, di, uo) is det.

printn(Stream, N, String, !S) :-

       ( N > 0 ->
               print(Stream, String, !S),
               printn(Stream, N - 1, String, !S)
       ; true ).</lang>

Mirah

<lang mirah>x = StringBuilder.new

5.times do

   x.append "ha"

end

puts x # ==> "hahahahaha"</lang>

MUMPS

<lang MUMPS>RPTSTR(S,N)

;Repeat a string S for N times
NEW I
FOR I=1:1:N WRITE S
KILL I
QUIT

RPTSTR1(S,N) ;Functionally equivalent, but denser to read

F I=1:1:N W S
Q</lang>

NewLISP

<lang NewLISP>(dup "ha" 5)</lang>

NetRexx

NetRexx has built in functions to manipulate strings. The most appropriate for this task is the copies() function: <lang NetRexx>/* NetRexx */

ha5 = 'ha'.copies(5) </lang>

Objeck

<lang objeck>bundle Default {

 class Repeat {
   function : Main(args : String[]) ~ Nil {
     Repeat("ha", 5)->PrintLine();
   }
   
   function : Repeat(string : String, max : Int) ~ String {
     repeat : String := String->New();
     for(i := 0; i < max; i += 1;) {
       repeat->Append(string);
     };
     
     return repeat;
   }
 }

}</lang>

Objective-C

Objective-C allows developers to extend existing an existing class by adding additional methods to the class without needing to subclass. These extensions are called categories. Category methods are available to all instances of the class, as well as any instances of its subclasses.

This task provides us with an opportunity to visit this aspect of the language feature.

We will extend NSString, the de facto Objective-C string class in environments that are either compatible with or descend directly from the OPENSTEP specification, such as GNUstep and Mac OS X, respectively, with a method that accomplishes the described task.

<lang objc>@interface NSString (RosettaCodeAddition) - (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times; @end

@implementation NSString (RosettaCodeAddition) - (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times {

   return [@"" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];

} @end</lang>

Now, let's put it to use: <lang objc> // Instantiate an NSString by sending an NSString literal our new

   // -repeatByNumberOfTimes: selector.
   NSString *aString = [@"ha" repeatStringByNumberOfTimes:5];
   // Display the NSString.
   NSLog(@"%@", aString);</lang>

OCaml

<lang ocaml>let string_repeat s n =

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

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

Alternately: <lang ocaml>let string_repeat s n =

 String.concat "" (Array.to_list (Array.make n s))
</lang>

Or: <lang ocaml>let string_repeat s n =

 Array.fold_left (^) "" (Array.make n s)
</lang>

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

OpenEdge/Progress

<lang Progress (OpenEdge ABL)>MESSAGE FILL( "ha", 5 ) VIEW-AS ALERT-BOX.</lang>

Oz

We have to write a function for this: <lang oz>declare

 fun {Repeat Xs N}
    if N > 0 then
       {Append Xs {Repeat Xs N-1}}
    else
       nil
    end
 end

in

 {System.showInfo {Repeat "Ha" 5}}</lang>

PARI/GP

This solution is unimaginably bad. Slightly less bad versions can be designed, but that's not the point: don't use GP for text processing if you can avoid it. If you really need to, it's easy to create an efficient function in PARI (see C) and pass that to GP. <lang parigp>repeat(s,n)={

 if(n, Str(repeat(s, n-1), s), "")

};</lang>

Pascal

See Delphi

Perl

<lang perl>"ha" x 5</lang>

Perl 6

Works with: Rakudo version #21 "Seattle"

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

PHP

<lang php>str_repeat("ha", 5)</lang>

PicoLisp

<lang PicoLisp>(pack (need 5 "ha")) -> "hahahahaha"</lang> or: <lang PicoLisp>(pack (make (do 5 (link "ha")))) -> "hahahahaha"</lang>

Pike

<lang pike>"ha"*5;</lang>

PL/I

<lang PL/I>s = copy('ha', 5);

/* To repeat a single character a fixed number of times: */

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

PostScript

<lang PostScript>% the comments show the stack content after the line was executed % where rcount is the repeat count, "o" is for orignal, % "f" is for final, and iter is the for loop variable % % usage: rcount ostring times -> fstring

/times {

 dup length dup    % rcount ostring olength olength
 4 3 roll          % ostring olength olength rcount
 mul dup string    % ostring olength flength fstring
 4 1 roll          % fstring ostring olength flength
 1 sub 0 3 1 roll  % fstring ostring 0 olength flength_minus_one 
 {                 % fstring ostring iter
   1 index 3 index % fstring ostring iter ostring fstring
   3 1 roll        % fstring ostring fstring iter ostring
   putinterval     % fstring ostring
 } for
 pop               % fstring

} def</lang>

PowerBASIC

<lang powerbasic>MSGBOX REPEAT$(5, "ha")</lang>

PowerShell

<lang powershell>"ha" * 5 # ==> "hahahahaha"</lang>

Prolog

<lang prolog>%repeat(Str,Num,Res). repeat(Str,1,Str). repeat(Str,Num,Res):-

   Num1 is Num-1,
   repeat(Str,Num1,Res1),
   string_concat(Str, Res1, Res).</lang>

Pure

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

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

PureBasic

<lang PureBasic>Procedure.s RepeatString(count, text$=" ")

  Protected i, ret$=""
  For i = 1 To count
     ret$ + text$
  Next
  ProcedureReturn ret$

EndProcedure

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

Python

<lang python>"ha" * 5 # ==> "hahahahaha"</lang> "Characters" are just strings of length one.

the other way also works: <lang python>5 * "ha" # ==> "hahahahaha"</lang>

R

<lang ruby>paste(rep("ha",5), collapse=)</lang>

Racket

For small n: <lang scheme>; fast (define (string-repeat n str)

 (apply string-append (make-list n str)))

(string-repeat 5 "ha") ==> "hahahahaha"</lang>

For very large n: <lang scheme>; memory efficient (define (string-repeat n string)

 (with-output-to-string 
  (λ ()
    (for ([_ (in-range n)])
      (display string)))))

(string-repeat 5 "ha") ==> "hahahahaha"</lang>

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

REBOL

<lang rebol>head insert/dup "" "ha" 5</lang>

Retro

<lang Retro>with strings'

repeatString ( $n-$ )
 1- [ dup ] dip [ over prepend ] times nip ;

"ha" 5 repeatString</lang>

REXX

<lang REXX>

              /*all examples are equivalent, but not created equal.*/


/*---------------------*/

y='ha' z=copies(y,5)

/*---------------------*/

y='ha' z = copies( 'ha', 5 )

/*---------------------*/

y='ha' z=y||y||y||y||y

/*---------------------*/

y= 'ha' z= y || y || y || y || y

/*---------------------*/

y='ha' z=

 do 5
 z=z || y
 end

/*---------------------*/

y="ha" z=

 do 5
 z=z||y
 end

/*---------------------*/ </lang>

Ruby

<lang ruby>"ha" * 5 # ==> "hahahahaha"</lang> Despite the use of the * operator, the operation is not commutative: <lang ruby>5 * "ha" # TypeError: String can't be coerced into Fixnum</lang>

Scala

<lang scala>"ha" * 5 // ==> "hahahahaha"</lang>

Scheme

<lang scheme>(define (string-repeat n str)

 (apply string-append (vector->list (make-vector n str))))</lang>

with SRFI 1: <lang scheme>(define (string-repeat n str) (fold string-append "" (make-list n str))) (string-repeat 5 "ha") ==> "hahahahaha"</lang>

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

Scratch

This example requires making variables named "String", "Count", and "Repeated" first.

sed

Number of ampersands indicates number of repetitions. <lang sed> $ echo ha | sed 's/.*/&&&&&/' hahahahaha </lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

 begin
   writeln("ha" mult 5);
 end func;</lang>

Output:

hahahahaha

SNOBOL4

<lang snobol4> output = dupl("ha",5) end</lang>

SQL

<lang sql>select rpad(, 10, 'ha')</lang>

Standard ML

<lang sml>fun string_repeat (s, n) =

 concat (List.tabulate (n, fn _ => s))
</lang>

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

To repeat a single character: <lang sml>fun char_repeat (c, n) =

 implode (List.tabulate (n, fn _ => c))
</lang>

Suneido

<lang Suneido>'ha'.Repeat(5) --> "hahahahaha" '*'.Repeat(5) --> "*****"</lang>

Tcl

<lang tcl>string repeat "ha" 5  ;# => hahahahaha</lang>

TUSCRIPT

<lang tuscript>$$ MODE TUSCRIPT SET text="ha" SET text=REPEAT (text,5)</lang>

UNIX Shell

Works with: Bash

<lang bash>printf "ha%.0s" {1..5}</lang> A slightly more generic version <lang bash>repeat() {

 eval "printf '${1}%.0s' {1..${2}}"

}</lang>

Using head -c

head -c is a GNU extension, so it only works with those systems. (Also, this script can only repeat a single character.)

Works with: Bourne Shell

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

Ursala

<lang Ursala>#import nat

repeat = ^|DlSL/~& iota

  1. cast %s

example = repeat('ha',5)</lang> output:

'hahahahaha'

Vala

Repeat a string 5 times: <lang vala> string s = "ha"; string copy = ""; for (int x = 0; x < 5; x++) copy += s; </lang>

Fill a string with a char N times: <lang vala> string s = string.nfill(5, 'c'); </lang>

VBA

<lang VBA> Public Function RepeatStr(aString As String, aNumber As Integer) As String Dim bString As String

bString = aString If aNumber > 1 Then

 For i = 2 To aNumber
   bString = bString & aString
 Next i

End If RepeatStr = bString End Function </lang>

Sample output:

print RepeatSTr( "Hello world!", 3)
Hello world!Hello world!Hello world!

Note: unlike Visual Basic .NET, "String(5, "ha") in VBA produces "hhhhh" (only the first character is repeated)!

Visual Basic .NET

Use the PadLeft & PadRight commands: <lang vbnet>FileContents = "X".PadRight(FileSizeBytes - 1, "X")

Where:

  • FileContents is the string to populate
  • FileSizeBytes is the number of repetitions (Remember that "-1" is valid as we have already specified the first character as being "X", which is to be padded on.

</lang> This produces:

"XXXXXXXXXX...........XXXXXXXXX"

Yorick

<lang yorick>array("ha", 5)(sum)</lang>