Android: Formatting Strings

Introduction
If you are java developer you can use String.format for adding some parameters into your string. Core Java provides us mechanism to manage it using symbols like %s or {1}, but how to use this mechanism in Android resource strings?

Resource Strings
Android provides us good mechanism to format strings in application too. Just try to add %1$s  or %1$d into your resource strings. The last symbols mean

  • s –  for string formatting
  • d – for decimal formatting

So, simple example:

<string name=“my_name”>My name is %1$s.</string>
<string name=“my_age”>I am %1$d years old.</string>

Here is we can see two types of using, the first is string formatting the second is number. In java code you have to add just simple String.format like in Core Java.

Resources res = getResources();
String myNameString = String.format(res.getString(R.string.my_name), “Tom”);
String myAgeString = String.format(res.getString(R.string.my_age), 25);

And that is all …

P.S. If you want to use more parameters in string just increase a number  %1$d ,%2$d ,%3$d

Cheers!

READ  Reverse LinkedList {Recursion implementation}

Leave a Reply

Your email address will not be published. Required fields are marked *