如何在Java Formatter中转义减号?

时间:2018-06-21 17:36:44

标签: java string formatting command-line-interface

以下是格式化的表格标题示例:

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
formatter.format("%-16s ---%-21s--- %-21s %-23s %-25s", "IP", "BLOCKED", "BLOCKED TILL", "ACTIVITY (00:00-24:00)", "COUNTRY");
System.out.println(sb.toString());

但是问题出在---%-21s---部分:

IP               ---BLOCKED              --- BLOCKED TILL          ACTIVITY (00:00-24:00)  COUNTRY

如何逃避最后三个减号?我想强调排序列。结果应为:

IP               ---BLOCKED---               BLOCKED TILL          ACTIVITY (00:00-24:00)  COUNTRY

1 个答案:

答案 0 :(得分:2)

问题是您将BLOCKED字符串指定为21的宽度,因此破折号---不能立即包围文本(请注意第二组破折号是在一串之后出现的)的空间)。相反,您必须将破折号放在要打印的字符串内:

formatter.format("%-16s %-21s %-21s %-23s %-25s", "IP", "---BLOCKED---", "BLOCKED TILL", "ACTIVITY (00:00-24:00)", "COUNTRY");