android String.format() uses

Usually splicing strings, it is estimated that they are connected with + at the beginning. If there are too many strings spliced, sometimes it is not easy to read. In order to solve this problem, I used the advanced method String.format() several years ago. Time It is easy to forget after a long time, here is how to use it;

<string name="str_format" formatted="false">%s_%s_%d</string>

String str = String.format(getString(R.string.str_format), "aa", "bb", 100);
Log.d("Alexx", "str: " + str);

Output: str: aa_bb_100

Use a very simple, standard way of writing, write the format string in the resource file,

%s represents a string placeholder, %d represents an integer placeholder,

In fact, there are many other %x placeholders, strings and integers are the most commonly used, and there are many other online materials, so I won’t go into details here;

The formatted="false" in the resource file means no formatting, if this is added, the string will not be formatted into other unwanted stuff;

When the mobile phone switches languages, there will be a problem with the above code, that is, it may be converted into other languages, so there is another method,

String str = String.format(Locale.ENGLISH, getString(R.string.str_format), "aa", "bb", 100);

Using Locale, this class can specify the language environment. For example, if the above code specifies the English environment, then no matter what language the phone switches to, it will only output English;

Well, it's time to play again.

Guess you like

Origin blog.csdn.net/msn465780/article/details/128266306