Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Dynamic String: %1d vs %1$d

Is there a difference between a format string with the $ included?

%1d vs %1$d

I noticed that in the app code we have both and both seems to work ok.

or by the way using %1d to %2d vs %1$d to %2$d

like image 445
htafoya Avatar asked Mar 28 '19 18:03

htafoya


People also ask

What is string format in Android?

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings: String. XML resource that provides a single string. String Array.

Which of the format string is not valid?

Format string XXX is not a valid format string so it should not be passed to String.

What is string XML file in Android?

String Array. XML resource that provides an array of strings. Quantity Strings (Plurals) XML resource that carries different strings for pluralization. All strings are capable of applying some styling markup and formatting arguments.

What is string format in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax: There is two types of string format() method.


1 Answers

%d - just display number

int first = 10;
System.out.printf("%d", first);
// output:
// 10

%1d - display number with information how much space should be "reserved" (at least one)

int first = 10;
System.out.printf("->%1d<-", first);
// output:
// ->10<-

%9d - reserve "9" chars (if number will be shorter - put spaces there) and align to right

int first = 10;
System.out.printf("->%9d<-", first);
// output:
// ->       10<-
//   123456789

%-9d - same as above but align to LEFT (this minus is important)

int first = 10;
System.out.printf("->%-9d<-", first);
// output:
// ->10       <-
//   123456789

%1$d - use (in format) position of the element from varargs (so you can REUSE elements instead of passing them two times)

int first = 10;
int second = 20;
System.out.printf("%1$d %2$d %1$d", first, second);
// output:
// 10 20 10

%1$9d - mix two of them. Get first parameter (1$) and reserve nine chars (%9d)

int first = 10;
System.out.printf("->%1$9d<-", first);
// output:
// ->       10<-
//   123456789
like image 164
Boken Avatar answered Nov 11 '22 09:11

Boken