2015-05-07 55 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);