Created
November 24, 2023 13:20
-
-
Save mutkuensert/89cb8bc3bf3b492c6a462fb90b087a97 to your computer and use it in GitHub Desktop.
My String extensions for Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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