[英]String.format and arrays
有沒有一種方法可以方便地使用String.format
(或printf)來打印數組中的值。 例:
public static void main(String[] args) {
System.out.printf("Today is %tc and your args are %TAG", new Date(), args);
}
我正在尋找的輸出:
Today is Sat Oct 14 14:54:51 CEST 2017 and your args are uno dos tres
如示例所示,我不知道args
數組有多長時間? 到目前為止,我想出的唯一解決方案是首先使用.format
來獲取字符串的第一部分,然后遍歷args數組並追加空格分隔的塊。
您有Arrays.toString(...)
,它將把它格式化為[“ unos”,“ dos”,tres“],但是我認為那不是您想要的。
通常,我使用流式api將結果收集到字符串中: Arrays.stream(args).collect(Collectors.joining(" "));
public static void main(String[] args) {
System.out.printf("Today is %tc and your args are %s%n", new Date(),
Arrays.stream(args).collect(Collectors.joining(" ")));
}
由於它不是原始數組,因此可以將args
包裝在列表中:
System.out.printf("%Tc %s", new Date(), Arrays.asList(args));
然后,將toString
的實現用於List
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.