Strings Początkujący

Repeat a string n times without a loop.

✕ Java 8
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
    sb.append("abc");
}
String result = sb.toString();
✓ Java 11+
String result = "abc".repeat(3);
// "abcabcabc"
Widzisz problem z tym kodem? Daj nam znać.
📏

One-liner

Replace 5 lines of StringBuilder code with one call.

Optimized

Internal implementation is optimized for large repeats.

📖

Clear intent

repeat(3) immediately conveys the purpose.

Stare podejście
StringBuilder Loop
Nowoczesne podejście
repeat()
Od JDK
11
Poziom trudności
Początkujący
String.repeat()
Dostępne

Widely available since JDK 11 (Sept 2018)

String.repeat(int) returns the string concatenated with itself n times. Handles edge cases: repeat(0) returns empty string, repeat(1) returns the same string.

Udostępnij 𝕏 🦋 in