如何使用String.format在现有的字符串中添加5个复数?[重复]

问题描述 投票:0回答:2

如何使用String.format在一个现有的字符串中添加5个复数?

我知道这种方式可以在现有的行中添加空格。

String str = "Hello";
String padded = String.format("%-10s", str);

如何添加加号? 我没找到加号是怎么表示的.

结果应该是。

"Hello+++++"
java string string-concatenation string.format
2个回答
3
投票

没有任何标志可以让你加垫子 + 而不是空间。相反,你需要做一些类似:

String.format("%s%s", str, "+".repeat(5))

或者干脆用:

str + ("+".repeat(5))

String.repeat 是在Java 11中引入的。

你也可以直接硬编码。

String.format("%s+++++", str)

1
投票
String str = "Hello"

String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";

1
投票

String.format("%s%s", str, "+++");

这应该可以用。


1
投票
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);
© www.soinside.com 2019 - 2024. All rights reserved.