Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format an array of strings with arguments

I'd like to format an array of strings just like android used to format strings:

Usually we do:

  • strings.xml

    <string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
    
  • In some java code:

    Resources res = getResources();
    String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
    

I'm looking for something like:

  • in some arbitrary xml:

        <string-array name="employee">
            <item>name: %1$s</item>
            <item>post: %2$s</item>
        </string-array>
    
  • in some java code:

    Resources res = getResources();
    String[] employee = ArrayString.format(res.getStringArray(R.string.employee), name, post);
    

Is there an elegant way to do that?

EDIT:

The next pieces of code is a workaround and I'm posting it just to help @Sufian, who asked for it in a comment. It's not a real answer once my question is about format the string array's content and the bellow code is formatting each string separately.

In some misc.xml:

<string-array
    name="string_array">
    <item>1st position: %1$d</item>
    <item>2nd position: %1$d</item>
</string-array>

Then, in java code:

res = getResources();
String[] sa = res.getStringArray(R.array.string_array);
for (int i = 0; i < sa.length; i++ ) {
    text += String.format(sa[i], i);
}
like image 386
Plinio.Santos Avatar asked Apr 17 '13 12:04

Plinio.Santos


1 Answers

Just use:

String text = String.format(res.getStringArray(R.array.myStringArray)[index], param1, param2);
like image 120
vitorvigano Avatar answered Oct 17 '22 00:10

vitorvigano