Suppose you have the following string:
String s = \"The cold hand reaches for the %1$s %2$s Ellesse\'s\";
String old = \"old\";
String tan = \"tan\";
String fo
I needed to replace %s
placeholders in a String by a set of Spannables, and didn't find anything satisfying enough, so I implemented my own formatter as a kotlin String extension. Hopes it helps anyone.
fun String.formatSpannable(vararg spans: CharSequence?): Spannable {
val result = SpannableStringBuilder()
when {
spans.size != this.split("%s").size - 1 ->
Log.e("formatSpannable",
"cannot format '$this' with ${spans.size} arguments")
!this.contains("%s") -> result.append(this)
else -> {
var str = this
var spanIndex = 0
while (str.contains("%s")) {
val preStr = str.substring(0, str.indexOf("%s"))
result.append(preStr)
result.append(spans[spanIndex] ?: "")
str = str.substring(str.indexOf("%s") + 2)
spanIndex++
}
if (str.isNotEmpty()) {
result.append(str)
}
}
}
return result
}
and then usage as follows
"hello %s kotlin %s world".formatSpannable(span0, span1)