Simple way to repeat a string
In Java, you can use the String.repeat()
method to repeat a string multiple times. This method was introduced in Java 11, so it is only available if you are using Java 11 or a later version.
Here is an example of how to use String.repeat()
:
String s = "abc";
int n = 3;
String repeated = s.repeat(n);
System.out.println(repeated); // Outputs "abcabcabc"
Alternatively, you can use a loop to repeat a string multiple times. Here is an example of how to do this:
String s = "abc";
int n = 3;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(s);
}
String repeated = sb.toString();
System.out.println(repeated); // Outputs "abcabcabc"
This code creates a StringBuilder
and appends the string s
to it n
times. It then converts the StringBuilder
to a String
using the toString()
method.