Created
May 20, 2019 13:48
-
-
Save fluidsonic/1a356448e20db7ee26b1fd43b94f570c to your computer and use it in GitHub Desktop.
StringBuilder.replace
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
actual fun StringBuilder.replace(start: Int, end: Int, replacement: String) = apply { | |
check(start in 0 .. length) { "start must be in 0 .. $length: $start" } | |
check(end in start .. length) { "end must be in $start .. $length: $end" } | |
when { | |
start == end -> Unit | |
start == 0 -> | |
when (end) { | |
length -> { | |
clear() | |
append(replacement) | |
} | |
else -> { | |
val string = substring(startIndex = end) | |
clear() | |
append(replacement) | |
append(string) | |
} | |
} | |
end == length -> { | |
val string = substring(startIndex = 0, endIndex = start) | |
clear() | |
append(string) | |
append(replacement) | |
} | |
else -> { | |
val before = substring(startIndex = 0, endIndex = start) | |
val after = substring(startIndex = end, endIndex = length) | |
clear() | |
append(before) | |
append(replacement) | |
append(after) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment