如何使用 String.format 向现有字符串添加 5 个加号?
How to add 5 pluses to an existing string using String.format?
如何使用 String.format 向现有字符串添加 5 个加号?
我知道您可以通过这种方式向现有行添加空格:
String str = "Hello";
String padded = String.format("%-10s", str);
如何加plus?
我没找到加号是怎么表示的。
结果应该是:
"Hello+++++"
String str = "Hello";
String padded = String.format("%s+++++", str);
System.out.println(padded);
?
如果你想让它更通用并将它提取到方法中,你可以尝试这样做:
String str = "Hello";
int size = 10;
String pluses = "";
for (int i = 0; i < size; i++) pluses = String.format("%s+", pluses);
String padded = String.format("%s%s", str, pluses);
System.out.println(padded);
String str = "Hello"
String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";
没有允许您填充 +
而不是 space 的标记。相反,您需要执行以下操作:
String.format("%s%s", str, "+".repeat(5))
或者只是:
str + ("+".repeat(5))
String.repeat
是在 Java 11.
中引入的
您也可以对其进行硬编码:
String.format("%s+++++", str)
String.format("%s%s", str, "++++");
这应该有效。
如何使用 String.format 向现有字符串添加 5 个加号?
我知道您可以通过这种方式向现有行添加空格:
String str = "Hello";
String padded = String.format("%-10s", str);
如何加plus? 我没找到加号是怎么表示的。
结果应该是:
"Hello+++++"
String str = "Hello";
String padded = String.format("%s+++++", str);
System.out.println(padded);
? 如果你想让它更通用并将它提取到方法中,你可以尝试这样做:
String str = "Hello";
int size = 10;
String pluses = "";
for (int i = 0; i < size; i++) pluses = String.format("%s+", pluses);
String padded = String.format("%s%s", str, pluses);
System.out.println(padded);
String str = "Hello"
String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";
没有允许您填充 +
而不是 space 的标记。相反,您需要执行以下操作:
String.format("%s%s", str, "+".repeat(5))
或者只是:
str + ("+".repeat(5))
String.repeat
是在 Java 11.
您也可以对其进行硬编码:
String.format("%s+++++", str)
String.format("%s%s", str, "++++");
这应该有效。