akash
akash

Reputation: 167

Getting rid of extra space character in an interpolated string

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.

Upvotes: 1

Views: 402

Answers (3)

Sweeper
Sweeper

Reputation: 271945

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")
}

Upvotes: 2

Mohamed Rejeb
Mohamed Rejeb

Reputation: 2629

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

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

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

Upvotes: 1

Tenfour04
Tenfour04

Reputation: 93659

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")
}

Upvotes: 2

Related Questions