java - 如何填充格式化字符串

标签 java

这似乎是一个简单的问题,但老实说我似乎没有解决这个问题。
我有一个格式化字符串,如下所示:

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 个字符。

10Formatter宽度类(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/

相关文章:

java - 将 s 识别为元音后最后一个字符的正则表达式模式

java - 如何使用 vaadin ClassResource 类和 Tomcat 作为 Web 服务器显示图像?

eclipse : Using same output folder for different projects

java - 长数删除第一位 - Fast Way JAVA

java - Redis 在运行时获取命令不可预测的结果

java - 我应该使用 AOP 来解决这个横切关注点吗?

java - 正则表达式能否提取一个子字符串,特别是在不包含第一个子字符串之后?

java - 是否可以使用表单调用 servlet?

java - 使用 SimpleDateFormat 将字符串转换为日期会返回随机日期

Java:关闭流:即使在 close() 之后流也为非 NULL