KT-2503 Added String.repeat method
#KT-2503 fixed
This commit is contained in:
committed by
Evgeny Gerashchenko
parent
712fafddb6
commit
7ccded5f6d
@@ -63,3 +63,18 @@ public inline fun String.count(predicate: (Char) -> Boolean): Int {
|
||||
}
|
||||
return answer
|
||||
}
|
||||
|
||||
/**
|
||||
* Repeats a given string n times.
|
||||
* When n < 0, IllegalArgumentException is thrown.
|
||||
* @includeFunctionBody ../../test/StringTest.kt repeat
|
||||
*/
|
||||
public inline fun String.repeat(n: Int): String {
|
||||
require(n >= 0, { "Cannot repeat string $n times" })
|
||||
|
||||
var sb = StringBuilder()
|
||||
for (i in 1..n) {
|
||||
sb.append(this)
|
||||
}
|
||||
return sb.toString()
|
||||
}
|
||||
|
||||
@@ -49,4 +49,12 @@ class StringTest {
|
||||
assertEquals("uRL", "URL".decapitalize())
|
||||
}
|
||||
|
||||
test fun repeat() {
|
||||
fails{ "foo".repeat(-1) }
|
||||
assertEquals("", "foo".repeat(0))
|
||||
assertEquals("foo", "foo".repeat(1))
|
||||
assertEquals("foofoo", "foo".repeat(2))
|
||||
assertEquals("foofoofoo", "foo".repeat(3))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user