Before JDK 11, a solution could be quickly provided via StringBuilder, as follows:
public static String concatRepeat(String str, int n) {
StringBuilder sb = new StringBuilder(str.length() * n);
for (int i = 1; i <= n; i++) {
sb.append(str);
}
return sb.toString();
}
Starting with JDK 11, the solution relies on the String.repeat(int count) method. This method returns a string resulting from concatenating this string count times. Behind the scenes, this method uses System.arraycopy(), which makes this very fast:
String result = "hello".repeat(5);
Other solutions that can fit well in different scenarios are listed as follows:
- Following is a String.join()-based solution:
String result = String.join("", Collections.nCopies(5, TEXT));
- Following is a Stream.generate()-based solution:
String result = Stream.generate(() -> TEXT)
.limit(5)
.collect(joining());
- Following is a String.format()-based solution:
String result = String.format("%0" + 5 + "d", 0)
.replace("0", TEXT);
- Following is a char[] based solution:
String result = new String(new char[5]).replace(" ", TEXT);
To check whether a string is a sequence of the same substring, rely on the following method:
public static boolean hasOnlySubstrings(String str) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length() / 2; i++) {
sb.append(str.charAt(i));
String resultStr = str.replaceAll(sb.toString(), "");
if (resultStr.length() == 0) {
return true;
}
}
return false;
}
The solution loops half of the given string and progressively replaces it with "", a substring build, by appending the original string in StringBuilder, character by character. If these replacements result in an empty string, it means that the given string is a sequence of the same substring.