Repeat a string

From Rosetta Code
Revision as of 19:15, 13 January 2010 by rosettacode>IanOsgood (→‎{{header|Forth}}: standard FILL to repeat single char)
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”, you might want to show that as well (i.e. repeat-char("*", 5) => "*****").

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>

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 = (char *)calloc(n*slen+1, sizeof(char));
 int i; char * p;
 for ( i=0, p = dest; i < n; ++i, p += slen ) {
   memcpy(p, s, slen);
 }
 return dest;

}

int main() {

 printf("%s\n", string_repeat(5, "ha"));
 return 0;

}</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 = (char *)calloc(n+1, sizeof(char));
 memset(dest, c, n);
 return dest;

}

int main() {

 printf("%s\n", char_repeat(5, '*'));
 return 0;

}</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>

C#

<lang csharp> String s = "".PadLeft(5, 'X').Replace("X", "ha")</lang>

To repeat a single character: <lang csharp> String s = "".PadLeft(5, '*')</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; import std.string;

void main() {

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

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

void main() {

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

}</lang>

E

<lang e>"ha" * 5</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 ;

create test 256 allot s" ha" test 5 place-n test count type \ hahahahaha

test 10 char * fill \ repeat a single character test 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

Haskell

For a string of finite length:

<lang haskell>concat $ replicate 5 "ha"</lang>

For an infinitely long string:

<lang haskell>cycle "ha"</lang>

To repeat a single character:

<lang haskell>replicate 5 '*'</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 function 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>

JavaScript

This solution creates an array of n+1 null elements, then joins them using the target string as the delimiter <lang javascript>String.prototype.repeat = function(n) {

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

}

alert("ha".repeat(5)); // hahahahaha</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>

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>

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>

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>

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>

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>

Python

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

PowerShell

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

R

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

Ruby

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

Scala

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

Scheme

Works with: ?

<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>(string-make 5 #\*)</lang>

Tcl

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

Ursala

<lang Ursala>#import nat

repeat = ^|DlSL/~& iota

  1. cast %s

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

'hahahahaha'