Kotlin String - repeat() Function



The Kotlin string repeat() function is used to create a new string by repeating the original string a specified number of times.

This function can be useful in various scenarios, such as Creating repeated patterns in text, Formatting output with repeated characters, simplifying test cases, or data generation by creating repeated values.

This function is straightforward and can be combined with loops conditional logic to build more complex patterns.

Syntax

Following is the syntax of the Kotlin string repeat() function −

fun String.repeat(n: Int): String

Parameters

This function accepts an integer value as a parameter and that should not be a negative number. The integer represents the number of times to repeat a string.

Return value

This function returns a new string where the original string is repeated n times consecutively. If n is 0 it returns an empty string.

Example 1: Repeat a String

Following is the basic example of therepeat()function. Repeat a string multiple times −

fun main(args: Array<String>) {
   val str = "tutorialspoint "
   // repeat the string
   val new_string = str.repeat(2)
   println("Original string: "+str)
   println("Repeated string: "+new_string)
}

Output

Following is the output −

Original string: tutorialspoint 
Repeated string: tutorialspoint tutorialspoint

Example 2: Generate a Line Separator

This is another example of the repeat() function. We create a line separator by repeating the underscore 20 times −

fun main(args: Array<String>){
   val separator = "-"
   // create a line separator
   val line_separater = separator.repeat(20)
   println(line_separater)
   println("Kotlin")
   println(line_separater) 
}

Output

Following is the output −

--------------------
Kotlin
--------------------

Example 3: Generate a Pattern

Here, we create an example that creates a pattern using the repeat() function −

fun main(args: Array<String>) {
   val star = "*"
   val n = 5;
   val pattern = star.repeat(n)
   for (i in 1..3) {
      println(pattern)
   }
}

Output

Following is the output −

*****
*****
*****
kotlin_strings.htm
Advertisements