I want to create a string
which would contain a *
symbol n
times.
I only see this way:
val s = ""
val n = 100
for (j in 0 until n) {
s += "*"
}
But it looks ugly and it has a O(n^2) time complexity. Is there a way in Kotlin to do that without a loop with better time complexity?
Example 1 – Kotlin repeat() In this example, we will use a repeat statement to execute print statement 4 times. fun main(args: Array) { repeat(4) { println("Hello World!") } }
Using String's split() function The standard solution to split a string in Kotlin is with the native split() function, which takes one or more delimiters as an argument and splits the string around occurrences of the specified delimiters. The split() function returns a list of strings.
To find the length of string in Kotlin language, you can use String. length property. String. length property returns the number of characters in the string.
Inside main() , create a variable called numbers of type List<Int> because this will contain a read-only list of integers. Create a new List using the Kotlin standard library function listOf() , and pass in the elements of the list as arguments separated by commas.
The built in CharSequence.repeat
extension does this in an efficient way, see the source here.
val str: String = "*".repeat(100)
Of course, this will still require O(n) steps to create the string. However, using this built-in stdlib function has its advantages: it's cross-platform, easy to read, and can be improved in performance over time, if there's a more efficient solution. The loop inside it will probably be optimized by the compiler or the runtime anyway.
An alternative to the CharSequence.repeat is a CharArray with an init function:
CharArray(N, {i -> '*'}).joinToString(separator="")
This solution has the advantage that you can define prefix, postfix, and separator.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With