Replacing character is straight forward. We simply map the string characters, where character to be replaced is mapped to replacement. We get List<Char>
after the map operation. To convert it to a String, we can use the joinToString()
function ;
fun String.replace(char: Char, replacement: Char, ignoreCase: Boolean = false): String {
return map {
if (it.equals(char, ignoreCase)) replacement else it
}.joinToString("")
}
There are other long methods of doing the same thing.
Using StringBuilder
Using StringBuilder
fun String.replaceUsingBuilder(char: Char, replacement: Char, ignoreCase: Boolean = false): String {
return buildString {
this@replaceUsingBuilder.forEach {
append(if (it.equals(char, ignoreCase)) replacement else it)
}
}
}
Using new array
Using new array
fun String.replaceUsingNewArray(char: Char, replacement: Char, ignoreCase: Boolean = false): String {
val newArray = CharArray(length)
forEachIndexed { index, c ->
newArray[index] = if (c.equals(char, ignoreCase)) replacement else c
}
return newArray.concatToString()
}