Skip to content

Instantly share code, notes, and snippets.

@mutkuensert
Created November 24, 2023 13:20
Show Gist options
  • Save mutkuensert/89cb8bc3bf3b492c6a462fb90b087a97 to your computer and use it in GitHub Desktop.
Save mutkuensert/89cb8bc3bf3b492c6a462fb90b087a97 to your computer and use it in GitHub Desktop.
My String extensions for Kotlin
fun String.clipString(
firstIndex: Int,
lastIndex: Int,
includeOneChar: Boolean = true
): String {
var word = ""
if (lastIndex >= length) throw IndexOutOfBoundsException()
if (firstIndex == lastIndex) {
if (includeOneChar) {
return this[firstIndex].toString()
}
return ""
}
for (i in firstIndex..lastIndex) {
word += this[i]
}
return word
}
fun String.remove(s: String): String {
val index = indexOf(s)
return if (index != -1) {
clipString(0, (index - 1).coerceAtLeast(0), index == 1) +
clipString((index + s.length).coerceAtMost(lastIndex), lastIndex, false)
} else {
this
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment