Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format string to phone number kotlin alghorithm

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?

like image 651
onesector Avatar asked Nov 01 '25 10:11

onesector


2 Answers

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
like image 168
Tim Biegeleisen Avatar answered Nov 04 '25 05:11

Tim Biegeleisen


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.

like image 39
Tenfour04 Avatar answered Nov 04 '25 06:11

Tenfour04