【问题标题】:Getting rid of extra space character in an interpolated string消除插值字符串中的多余空格字符
【发布时间】:2022-10-04 21:32:31
【问题描述】:
你能帮我解决以下问题吗?
"${getFormattedMonthString(months)} ${getFormattedDayString(days)}, till now"
例如上面的字符串输出是---
1 Month 2 days, till now
但是如果 getFormattedDayString(days) 返回空字符串,输出将是——
1 Month , till now
如您所见,月后会有额外的空间。您能否建议在这里使用字符串插值的正确方法,这样我就可以摆脱多余的空间。
【问题讨论】:
标签:
string
kotlin
string-interpolation
【解决方案1】:
我会做一个名为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")
}
【解决方案2】:
仅当您要使用天数时,这才需要一个表达式来添加空间。使其成为外部代码行比尝试将其放入字符串语法要干净得多:
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")
}
【解决方案3】:
您可以使用.replace(" ,", ","):
"${getFormattedMonthString(months)} ${getFormattedDayString(days)}, till now".replace(" ,", ",")
现在你的字符串中的任何" ," 都将被"," 替换