How can I rewrite the code below using the function String.format() ?

 String s = getReference().getString(R.string.pre_text_main) + " " + str + " " + getReference().getString(R.string.post_text_main); getReference().endText.setText(s); 
  • one
    Your code is quite optimal, you do not need to change it. - Alexander Petrov

2 answers 2

The first option is good, but there is one more: you can immediately get the lines with the parameter for formatting. For example, your string resource:

 <string name="text_main">Какой-то пре-текст %s какой-то пост-текс</string> 

Then you can get this string resource in the code by immediately putting the right word instead of % s . Code example:

 getString(R.string.text_main, str) 

where, str is what will be in the parameter.

  • Thank you very much!!! you really helped !!! - Hayk Petrosyan
  • problem solved !!! - Hayk Petrosyan

String.format() takes as its first argument the format described in the Formatter class

In your case, it is necessary in the format to apply the s flag, which calls arg.toString()

 String prefix = getReference().getString(R.string.pre_text_main); String suffix = getReference().getString(R.string.post_text_main); getReference().endText.setText(String.format("%s %s %s", prefix, str, suffix)); 
  • Thank you very much!!! you really helped !!! - Hayk Petrosyan