Search code examples
androidregexkotlinsubstringtrim

How remove space and dash between three phone number and convert to list


I have one string phone number.

String phNum = "01 12 1234 123 - 124 - 125"

I want to change format like this.

List<String> listPhone= ("01121234123","01121234124","01121234125")

I don't know what method use trim or regex which is the best.Any soluctions?


Solution

  • Hi @HZan hope you doing well, I'm not that good at java but you can use kotlin snippet equivalent in java to get the desired result if the fold function isn't available, you could use forEach or any other accumulator pattern to achieve the same,

    val phNum = "01 12 1234 123 - 124 - 125"
    val phoneArray = phNum.toCharArray().filter{it.toString().isNotBlank()}
    val prefix = phoneArray.subList(0,8).joinToString("")
    val varientArray = phoneArray.subList(8,phoneArray.size).joinToString("").split("-")
    val result = varientArray.fold(mutableListOf<String>()){ list , suffix -> 
        list.add("$prefix$suffix")
        return@fold list
    }
    println(result)