|
How to generate a repeat String in Java
The following example shows generating a repeat string in java.
|
package com.bethecoder.articles.basics.str_repeat;
public class StringRepeatTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(repeat("BTC", 6));
System.out.println(repeat("Java", 4));
System.out.println(repeat("Abc", 6));
}
public static final String repeat(String str, int times) {
if (str == null) return null;
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < times ; i ++) {
sb.append(str);
}
return sb.toString();
}
}
|
| |
It gives the following output,
BTCBTCBTCBTCBTCBTC
JavaJavaJavaJava
AbcAbcAbcAbcAbcAbc
|
|