The repeat
function in Kotlin is used to create a new string by repeating the original string a specified number of times. This function belongs to the String
class in the Kotlin standard library and provides a straightforward way to repeat a string.
Table of Contents
- Introduction
repeat
Function Syntax- Understanding
repeat
- Examples
- Basic Usage
- Using
repeat
with Different Counts
- Real-World Use Case
- Conclusion
Introduction
The repeat
function generates a new string by repeating the original string a specified number of times. This is useful for tasks such as creating patterns, generating repeated content, and formatting output.
repeat Function Syntax
The syntax for the repeat
function is as follows:
fun String.repeat(n: Int): String
Parameters:
n
: The number of times to repeat the original string. This must be a non-negative integer.
Returns:
- A new string that consists of the original string repeated
n
times.
Throws:
IllegalArgumentException
ifn
is negative.
Understanding repeat
The repeat
function concatenates the original string with itself n
times to create a new string. If n
is 0, the function returns an empty string.
Examples
Basic Usage
To demonstrate the basic usage of repeat
, we will create a string and repeat it a specified number of times.
Example
fun main() {
val text = "Hello"
val repeatedText = text.repeat(3)
println("Original text: $text")
println("Repeated text: $repeatedText")
}
Output:
Original text: Hello
Repeated text: HelloHelloHello
Using repeat
with Different Counts
This example shows how to use repeat
with different repeat counts.
Example
fun main() {
val text = "Kotlin"
val repeatedOnce = text.repeat(1)
val repeatedTwice = text.repeat(2)
val repeatedZeroTimes = text.repeat(0)
println("Original text: $text")
println("Repeated once: $repeatedOnce")
println("Repeated twice: $repeatedTwice")
println("Repeated zero times: '$repeatedZeroTimes'")
}
Output:
Original text: Kotlin
Repeated once: Kotlin
Repeated twice: KotlinKotlin
Repeated zero times: ''
Real-World Use Case
Creating a Divider Line
In real-world applications, the repeat
function can be used to create repeated patterns, such as a divider line made of hyphens.
Example
fun main() {
val line = "-".repeat(30)
println(line)
println("Title")
println(line)
}
Output:
------------------------------
Title
------------------------------
Conclusion
The repeat
function in Kotlin's String
class is a convenient method for creating a new string by repeating the original string a specified number of times. It provides a simple way to generate repeated content for various use cases, including formatting, pattern creation, and generating repeated content.
By understanding and using this function, you can effectively manage string repetition in your Kotlin applications.
Comments
Post a Comment
Leave Comment