Home > Mobile >  Make string starts with specified prefix in Kotlin
Make string starts with specified prefix in Kotlin

Time:10-06

I am trying to find out the native way to concatenate prefix to string, but only in case, it was not.

This code checks the text variable and makes it start with "#".

val text = "123456"
val prefix = "#"
val textFormatted = (if (text.startsWith(prefix)) "" else prefix )   text

I hope there are clean solutions somewhere in Kotlin

CodePudding user response:

An alternative would be to use removePrefix:

val textFormatted = prefix   text.removePrefix(prefix)

Otherwise you could also keep the if but write it the following way to avoid extra parentheses and extra concatenation, and also make the code closer to the semantics:

val textFormatted = if (text.startsWith(prefix)) text else "$prefix$text"

But your solution works too.

CodePudding user response:

You can use the string interpolation from the kotlin, example:

val text:String = "123456"
val prefix:String = "#"
val interpolation:String = "#${text.replace("#", "")}"
  • Related