包含 $ 的格式字符串有区别吗?
%1d
对比 %1$d
我注意到在应用程序代码中我们同时拥有两者,而且两者似乎都可以正常工作。
或者顺便说一句,使用 %1d to %2d
vs %1$d to %2$d
最佳答案
%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 (thisminus
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
关于安卓动态字符串 : %1d vs %1$d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55404716/