Android 动态字符串:%1d 与 %1$d

hta*_*oya 5 string android string-formatting android-resources

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

%1d 对比 %1$d

我注意到在应用程序代码中我们都有,而且两者似乎都可以正常工作。

或者顺便说一下使用%1d to %2dvs%1$d to %2$d

Bok*_*ken 5

%d - 只显示数字

int first = 10;
System.out.printf("%d", first);
// output:
// 10
Run Code Online (Sandbox Code Playgroud)

%1d - 显示数字和信息应该“保留”多少空间(至少一个)

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

%9d - 保留“9”个字符(如果数字会更短 - 在那里放空格)并向右对齐

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

%-9d- 同上,但向左对齐(这minus很重要)

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

%1$d - 使用可变参数中元素的(格式)位置(因此您可以重用元素而不是将它们传递两次)

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

%1$9d- 混合其中两个。获取第一个参数 ( 1$) 并保留九个字符 ( %9d)

int first = 10;
System.out.printf("->%1$9d<-", first);
// output:
// ->       10<-
//   123456789
Run Code Online (Sandbox Code Playgroud)