安卓动态字符串 : %1d vs %1$d

标签 android string string-formatting android-resources

包含 $ 的格式字符串有区别吗?

%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 (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

关于安卓动态字符串 : %1d vs %1$d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55404716/

相关文章:

java - while(true) 循环不间断

android - 通过形状资源文件设置圆角的 ConstraintLayout 不起作用

Android 字符串变量 (HH :mm) to long variable miliseconds

java - 点后显示最多 X 位数字

java - BuildConfig.DEBUG(或等效项)作为常量值

带有日期选择器的 Android 微调器,例如 Google 日历应用

arrays - 在逻辑应用中拆分 HTTP 正文字符串时出现问题

java - 字符串(drawString)仅在滚动时消失(JAVA)

linux - 编辑文件时保留时间戳

c# - StringFormat 中的百分比