2015-05-07 42 views
4

C#中,您可以指定将哪个参数用于格式化字符串para 2: {2}。这允许在任意位置和多次使用参数。在String.format()中选择参数

有没有办法做到这一点与标准的Java?

+0

@RahulTripathi,是的,我再次检查了,所以我删除了标志。 –

+0

@DeepikaRajani: - 欣赏! –

回答

7

是的。您可以定义参数的索引,请参阅API参数索引部分。

例如:

//     ┌ argument 3 (1-indexed) 
//     | ┌ type of String 
//     | | ┌ argument 2 
//     | | | ┌ type of decimal integer 
//     | | | | ┌ argument 1 
//     | | | | | ┌ type of decimal number (float) 
//     | | | | | | 
System.out.printf("%3$s %2$d %1$f", 1.5f, 42, "foo"); 

输出

foo 42 1.500000 

注意

下列成语都有着相同的格式定义:

  • String#format
  • PrintStream#printf
  • Formatter#format
1

是。从https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax我们可以看到占位符的是通式为

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

我们感兴趣的是这部分

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

所以,你可以使用添加x$到您的占位符,其中x代表参数号码做(索引1)像

String.format("%2$s %1$s", "foo", "bar"); //returns `"bar foo"` 
//    ^^ ^^  ^^^ ^^^ 
//    | +-----+  | 
//    |     | 
//    +-----------------+ 

顺便说一句:如果你想使用格式化像{x}只是我们ËMessageFormat.format

MessageFormat.format("{1} {0}", "foo", "bar") 
1

我认为你正在使用指定的格式字符串和参数搜索String.format()

返回一个格式化字符串。

用途:

String.format("%1$s", object);