在写课程实验时遇到了给节点label增加序号的问题。这就需要补全高位的0。
这里用到了String.format()方法。
String类的format()方法用于创建格式化的字符串以及连接多个字符串对象。
String Label = "label"; String newLabel = String.format("%s%03d", Label, 7);//0是前面补全0的标志,3是位数 System.out.println(newLabel);
输出:
label007
同时String.format()方法还有许多种用法
下表总结了String.format()方法支持的标志。y表示该标志对于指定的参数类型是受支持的。
Flag | General | Character | Integral | Floating Point | Date/Time | Description |
---|---|---|---|---|---|---|
'-' | y | y | y | y | y | The result will be left-justified. |
'#' | y1 | - | y3 | y | - | The result should use a conversion-dependent alternate form |
'+' | - | - | y4 | y | - | The result will always include a sign |
' ' | - | - | y4 | y | - | The result will include a leading space for positive values |
'0' | - | - | y | y | - | The result will be zero-padded |
',' | - | - | y2 | y5 | - | The result will include locale-specific grouping separators |
'(' | - | - | y4 | y5 | - | The result will enclose negative numbers in parentheses |
1 Depends on the definition of Formattable
.
2 For 'd'
conversion only.
3 For 'o'
, 'x'
, and 'X'
conversions only.
4 For 'd'
, 'o'
, 'x'
, and 'X'
conversions applied to BigInteger
or 'd'
applied to byte
, Byte
, short
, Short
, int
and Integer
, long
, and Long
.
5 For 'e'
, 'E'
, 'f'
, 'g'
, and 'G'
conversions only.
具体用法见 Class Formatter