Home > Software design >  Android kotlin eliminate spaces before optional string placeholder
Android kotlin eliminate spaces before optional string placeholder

Time:01-03

Based on a string with multiple placeholders:

<string name="customer_info">Info: %1$s %2$s %3$s %4$s; ID=%5$s</string>

2, 3 and 4 may mostly be empty so without doing anything with the spaces I would end with this:

Info: John   ; ID=0293840
What I need: Info: John; ID=0293840

Solution 1 = Divide the string in 3:

<string name="customer_info">%1$s%2$s</string>
<string name="customer_info_part1">Info: %1$s %2$s %3$s %4$s</string>
<string name="customer_info_part2">; ID 1%s</string>

Is there a better solution using only one string?

I tried using regex: .replace("\\s ".toRegex(), " ") but this leads to Info: John ; ID=0293840 and I'm not sure if using regex in a view holder of list items would be better anyways.

CodePudding user response:

You can have Info: %1$s; ID=%2$s as the format string and then something like

yourInfosAsList
    .filterNot { it.isNullOrEmpty() }
    .joinToString(separator = " ")

to process the non-empty info items to a space-separated string.

CodePudding user response:

Whitespace collapsing and Android

Whitespace collapsing and Android escaping happens after your resource file gets parsed as XML. This means that     (space, punctuation space, Unicode Em space) all collapse to a single space (" "), because they are all Unicode spaces after the file is parsed as an XML. To preserve those spaces as they are, you can either quote them ("    ") or use Android escaping ( \u0032 \u8200 \u8195).

Recommend reading about String resources

  • Related