In this tutorial, you shall learn how to repeat a given string for N times in Kotlin, using String.repeat() function, with examples.

Kotlin – Repeat string N times

To repeat a string N times in Kotlin, you can use CharSequence.repeat() function.

Call the repeat() function on the string and pass the integer n (number of times) as argument to the function. The function returns a new string created by repeating this string n times.

Syntax

If str is the given string, then the syntax to repeat this string n times is

str.repeat(n)
ADVERTISEMENT

Examples

In the following program, we take a string in str, find a string that is repeat of the string str for n times.

Main.kt

fun main() {
    val str = "hello"
    val n = 3
    val output = str.repeat(n)
    println(output)
}

Output

hellohellohello

Conclusion

In this Kotlin Tutorial, we learned how to repeat a string n times using CharSequence.repeat() function.