I have the following texts. I need to add a single space between the string and numbers.
Text1 -> Text 1
Text10 -> Text 10
Kotlin2 -> Kotlin 2
I used the following code, but it does not work.
fun addSpace(text: String): String {
return text.split("\\s|\\D".toRegex()).joinToString(separator = " ") { it }
}
It return only the number.
>Solution :
You can just replace any occurrence of a string of digits with a space followed by those digits:
fun addSpace(text: String) = text.replace(Regex("\\d+" ), " \$0")
(The $ is escaped so that the Kotlin compiler doesn’t treat it as interpolation.)