在插值字符串中去掉多余的空格字符



您能帮我解决以下问题吗。

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

例如,上面的字符串输出是---

1 Month 2 days, till now

但是,如果getFormattedDayString(days(返回空字符串,则输出为--

1 Month , till now

正如你所看到的,月后会有额外的空间。你们能在这里建议使用字符串插值的正确方法吗,这样我就可以去掉多余的空间。

只有当您要使用天数时,才需要一个表达式来添加空格。将其作为外部代码行比尝试将其放入字符串语法中要干净得多:

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

或者您可以使用buildString函数来执行此操作。

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

我会做一个名为prependingSpaceIfNotEmpty:的扩展

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

然后:

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

不过,如果你有更多的组件,比如一年,我会选择buildString,类似于Tenfour的答案:

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

您可以使用.replace(" ,", ","):

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

现在,字符串中的任何" ,"都将被","替换

最新更新