Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

repeat string n times in Kotlin

Tags:

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?

like image 834
Rainmaker Avatar asked Jan 25 '18 15:01

Rainmaker


People also ask

How do you repeat a code on Kotlin?

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!") } }

How do you cut a string with Kotlin?

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.

What will be the length of the string Kotlin programs?

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.

How do I use a list on Kotlin?

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.


2 Answers

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.

like image 182
zsmb13 Avatar answered Oct 18 '22 00:10

zsmb13


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.

like image 20
Christian Kuka Avatar answered Oct 18 '22 01:10

Christian Kuka