Home > Software engineering >  How to format string to phone number kotlin alghorithm
How to format string to phone number kotlin alghorithm

Time:05-31

I get a string containing a phone number as input. This string looks like this:

79998886666

But I need to convert it to this form:

 7 999 888-66-66

I tried several ways, but the most recent one I got looks like this:

private fun formatPhone(phone: String): String {
    val prefix = " "
    val countryCode = phone.first()
    val regionCode = phone.dropLast(7).drop(1)
    val firstSub = phone.dropLast(4).drop(4)
    val secondSub = phone.dropLast(2).drop(7)
    val thirdSub = phone.drop(9)

    return "$prefix$countryCode $regionCode $firstSub-$secondSub-$thirdSub"
}

But it seems to me that this method looks rather strange and does not work very efficiently. How can this problem be solved differently?

CodePudding user response:

You could use a regex replacement here:

val regex = """(\d)(\d{3})(\d{3})(\d{2})(\d{2})""".toRegex()
val number = "79998886666"
val output = regex.replace(number, " $1 $2 $3-$4-$5")
println(output)  //  7 999 888-66-66

CodePudding user response:

You could create a helper function that returns chunks of the String at a time:

private fun formatPhone(phone: String): String {
    fun CharIterator.next(count: Int) = buildString { repeat(count) { append(next()) } }
    return with(phone.iterator()) {
        " ${next(1)} ${next(3)} ${next(3)}-${next(2)}-${next(2)}"
    }
}

Your original code could be simplified and made more performant by using substring instead of drop/dropLast.

  • Related