Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin – add a single space between string and number

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading