Repeat a string: Difference between revisions
Line 18: | Line 18: | ||
There's no function or operator to do this in Java, so you have to do it yourself. |
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){ |
<lang java5>public static String repeat(String str, int times){ |
||
StringBuilder ret = new StringBuilder( |
StringBuilder ret = new StringBuilder(); |
||
for(int i = |
for(int i = 0;i < times;i++) ret.append(str); |
||
return ret.toString(); |
return ret.toString(); |
||
} |
} |
||
Line 26: | Line 26: | ||
System.out.println(repeat("ha", 5)); |
System.out.println(repeat("ha", 5)); |
||
}</lang> |
}</lang> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
This solution creates an array of n+1 null elements, then joins them using the target string as the delimiter |
This solution creates an array of n+1 null elements, then joins them using the target string as the delimiter |
Revision as of 22:53, 21 October 2009
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"
E
<lang e>"ha" * 5</lang>
Haskell
<lang haskell>concat $ replicate 5 "ha"</lang>
J
<lang j>
5 ((* #) $ ]) 'ha'
hahahahaha </lang>
Java
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>
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>
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>
Perl
<lang perl>"ha" x 5</lang>
PHP
<lang php>str_repeat("ha", 5)</lang>
Python
<lang python>"ha" * 5 # ==> "hahahahaha"</lang>
Ruby
<lang ruby>"ha" * 5 # ==> "hahahahaha"</lang>
Tcl
<lang tcl>string repeat "ha" 5 ;# => hahahahaha</lang>