I'm afraid my solution is not very efficient:
fun String.mask() = if (isEmpty()) {
this
} else {
this[0] String((1 until length).map { '*' }.toCharArray())
}
How would you do it?
CodePudding user response:
One way is to use replaceRange
to do the replacing, and repeat
to construct the repeated asterisks:
fun String.mask() =
if (isEmpty())
""
else
replaceRange(1, length, "*".repeat(length - 1))
CodePudding user response:
You can just init an array full of *
and set the first character too:
fun String.mask() = if (isEmpty()) {
this
} else {
CharArray(length) { '*' }.also { it[0] = this[0] }.joinToString(separator = "")
}
actually since the init block for the array is a function, we can just do
CharArray(length) { i -> if (i == 0) this[0] else '*' }.joinToString("")
and you can use first()
instead of this[0]
if that's more readable