Home > Enterprise >  Getting rid of extra space character in an interpolated string
Getting rid of extra space character in an interpolated string

Time:10-04

can you please help me resolve the below issue.

"${getFormattedMonthString(months)} ${getFormattedDayString(days)}, till now"

for example above string output is ---

1 Month 2 days, till now

But if getFormattedDayString(days) returns empty string, The output will be --

1 Month , till now

As you can see there will extra space after Month. Can you please suggest right way to use string interpolation here, so i can get rid of extra space.

CodePudding user response:

I would make an extension called prependingSpaceIfNotEmpty:

fun String.prependingSpaceIfNotEmpty() = if (isNotEmpty()) " $this" else this

Then:

"${getFormattedMonthString(months)}${getFormattedDayString(days). prependingSpaceIfNotEmpty()}, till now"

Though if you have more components, like a year, I would go for buildString, similar to Tenfour's answer:

buildString { 
    append(getFormattedYear(year))
    append(getFormattedMonth(month).prependingSpaceIfNotEmpty())
    append(getFormattedDay(day).prependingSpaceIfNotEmpty())
    append(", till now")
}

CodePudding user response:

This requires an expression to add the space only if you are going to use the days. Much cleaner to make it an external line of code than to try to put it into the string syntax:

var daysString = getFormattedDayString(days)
if (daysString.isNotEmpty()) {
    daysString = " "   daysString
}
val output = "${getFormattedMonthString(months)}$daysString till now"

or you could use the buildString function to do this.

val output = buildString {
    append(getFormattedMonthString(months))
    val days = getFormattedDayString(days)
    if (days.isNotEmpty()) {
        append(" "   days)
    }
    append(" till now")
}

CodePudding user response:

You can use .replace(" ,", ","):

"${getFormattedMonthString(months)} ${getFormattedDayString(days)}, till now".replace(" ,", ",")

Now any " ," in your string in going to get replaced with ","

  • Related