is the a function to anonymise a String? i.e. to o...
# announcements
r
is the a function to anonymise a String? i.e. to only keep the last n digits and replace the rest with
*
?
j
Copy code
fun anonymise(s: String, n: Int): String {
        val replaceLength = kotlin.math.min(s.length, n)
        val replaceChars = String(CharArray(replaceLength, {'*'} ))
        return "$replaceChars${s.substring(replaceLength)}"
    }
    
    @Test
    fun `anonymise`() {
        anonymise("blah", 3).shouldBe("***h")
        anonymise("blah", 4).shouldBe("****")
        anonymise("blah", 5).shouldBe("****")
    }
👍 1
maybe someone can suggest something neater
r
thanks 🙂
👍 1
d
maybe an extension function is better
something like
Copy code
fun String.anonymise(numberOfCharactersToHide: Int = this.length - 1) =
        replaceRange(0,
                kotlin.math.min(this.length -1, numberOfCharactersToHide),
                "*")
it's untested, by default will replace all the characters but the last one
j
I hadn't come across
replaceRange
, totally the right tool for the job! kotlinlang is such a great slack channel
Ah, except that replaces the entire range with a single asterisk
Copy code
fun Char.times(n: Int) = String(CharArray(n, {this} ))

    fun String.anonymise(numberOfCharactersToHide: Int = this.length - 1): String {
        val resolvedCharacterToHide = kotlin.math.min(this.length, numberOfCharactersToHide)

        return replaceRange(
            0,
            resolvedCharacterToHide,
            '*'.times(resolvedCharacterToHide)
        )
    }

    @Test
    fun `anonymise`() {
        val s = "blah"
        s.anonymise(3).shouldBe("***h")
        s.anonymise(4).shouldBe("****")
        s.anonymise(5).shouldBe("****")
    }
a