Which do you prefer for removing all occurrences o...
# announcements
m
Which do you prefer for removing all occurrences of a specific hard-coded character?
Copy code
1. someString.replace(" ", "")
2. someString.filterNot { it == ' ' }
3. someString.filterNot(' '::equals)
1️⃣ 13
r
semantically
someString.replace(" ", "")
make more sense to me
m
Pretty decisive! Are there any situations where
String.filter()
would be useful? Perhaps this?
Copy code
fun String.removeAll(chars: CharArray): String {
    val charSet = chars.toSet()
    return filterNot(charSet::contains)
}

// usage example
someString.removeAll("!?{}".toCharArray())
Although even here, I’d be more tempted to do something like:
Copy code
class MultiCharRemover(vararg charsToRemove: Char) {
    private val regex = buildString {
        append('[')
        charsToRemove.forEach { c ->
            if (c in specialChars) {
                append('\\')
            }
            append(c)
        }
        append(']')
    }.toRegex()

    fun removeFrom(input: CharSequence): String = regex.replace(input, "")

    companion object {
        private val specialChars = setOf('^', '-', ']', '\\')
    }
}
r
I tend to define this:
Copy code
fun String.remove(value: String, ignoreCase: Boolean = false) = replace(value, "", ignoreCase)
👍 1