KT-2503 Added String.repeat method

#KT-2503 fixed
This commit is contained in:
Tommy Hallgren
2012-11-15 10:35:01 +01:00
committed by Evgeny Gerashchenko
parent 712fafddb6
commit 7ccded5f6d
2 changed files with 23 additions and 0 deletions
+15
View File
@@ -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()
}
+8
View File
@@ -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))
}
}