Repeat a string: Difference between revisions
Content added Content deleted
(→{{header|Java}}: code cleanup) |
|||
Line 898: | Line 898: | ||
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){ |
<lang java5>public static String repeat(String str, int times) { |
||
StringBuilder |
StringBuilder sb = new StringBuilder(str.length() * times); |
||
for(int i = 0;i < times;i++) |
for (int i = 0; i < times; i++) |
||
⚫ | |||
sb.append(str); |
|||
⚫ | |||
} |
} |
||
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> |
}</lang> |
||
Or even shorter: |
Or even shorter: |
||
<lang java5>public static String repeat(String str, int times){ |
<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> |
}</lang> |