Home > Blockchain >  Kotlin - add a single space between string and number
Kotlin - add a single space between string and number

Time:12-06

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.

CodePudding user response:

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.)

CodePudding user response:

You can use regex groups and replaceAll

fun main() {
    val input = "Text1 Text10 Kotlin2"
    val pattern = Pattern.compile("([a-zA-Z] )([0-9] )")
    val matcher = pattern.matcher(input).replaceAll("$1 $2")
    println(matcher)
}

Output will be

Text 1 Text 10 Kotlin 2

  • Related