这似乎是一个简单的问题,但老实说我似乎没有解决这个问题。
我有一个格式化字符串,如下所示:
String msg = String.format("Current player: %1$s", status.getCurrentPlayer().getName());
我想向左填充它,假设有 10 个空格。我尝试过:
String pad = String.format("%1$10s", msg);
但它似乎不起作用,尽管我尝试使用未格式化的字符串:
String pad = String.format("%1$10s", "some string");
显然,它起作用了。
“msg”是什么原因不允许我填充它?
最佳答案
What is it about "msg" that does not let me pad it?
长度超过 10 个字符。
10
是 Formatter
的宽度类(class)。
阅读该文档,您会发现
The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.
所以,最小值,意味着任何比按原样打印的字符串长的字符串。
如果要填充,只需在字符串长度上加10即可。
String msg = "some really, really long message";
String fmt = "%1$" + (10 + msg.length()) + "s";
String pad = String.format(fmt, msg);
// " some really, really long message"
关于java - 如何填充格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41202180/