Repeat a string: Difference between revisions
(added perl, php, python) |
(added haskell) |
||
Line 1: | Line 1: | ||
{{task|String manipulation}}Take a string and repeat it some number of times. Example: repeat("ha", 5) => "hahahahaha" |
{{task|String manipulation}}Take a string and repeat it some number of times. Example: repeat("ha", 5) => "hahahahaha" |
||
=={{header|Haskell}}== |
|||
<lang haskell>concat $ replicate 5 "ha"</lang> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
{{works with|Java|1.5+}} |
Revision as of 18:13, 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"
Haskell
<lang haskell>concat $ replicate 5 "ha"</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(str); for(int i = 1;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 empty array of size n+1 and then joins it 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>
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>