What does “%1$#” mean when used in String.format (Java)?

坚强是说给别人听的谎言 提交于 2019-12-03 11:34:07

问题


Language is Java. What does the %1$# mean in...

static String padright (String str, int num) {
   return String.format("%1$#" + num + "str", str);
}

In the Java API, String.format() is used in this way:

public static String format(String format, Object... args)

So I think %1$# is a format specifier.

%[flags][width][.precision][argsize]typechar is the template.

  • 1 is a flag?
  • $ is the width?
  • # is the precision?
  • num is the argsize?
  • "str" is the typechar?

Is that right?


回答1:


Template:

%[argument_index$][flags][width][.precision]conversion

The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.

The optional width is a decimal integer indicating the minimum number of characters to be written to the output.

The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.

The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

%1$ refers to the first substitution. In this case the string str. # is flag which says the result should use a conversion-dependent alternate form.

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html



来源:https://stackoverflow.com/questions/5762836/what-does-1-mean-when-used-in-string-format-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!