英文:
How to add 5 pluses to an existing string using String.format?
问题
怎样使用String.format在现有字符串中添加5个加号?
我知道可以通过以下方式在现有行中添加空格:
String str = "Hello";
String padded = String.format("%-10s", str);
怎样添加加号?
我没有找到如何表示加号符号。
结果应该是:
"Hello+++++";
英文:
How to add 5 pluses to an existing string using String.format?
I know that this way you can add spaces to an existing line:
String str = "Hello";
String padded = String.format("%-10s", str);
How to add plus?
I did not find how the plus symbol is indicated.
the result should be:
"Hello+++++"
答案1
得分: 3
没有标志允许您填充+
而不是空格。相反,您需要这样做:
String.format("%s%s", str, "+".repeat(5))
或者可能只需:
str + ("+".repeat(5))
String.repeat
是在Java 11中引入的。
您还可以直接编码:
String.format("%s+++++", str)
英文:
There is no flag that allows you to pad +
instead of space. Instead you need to do something like:
String.format("%s%s", str, "+".repeat(5))
or maybe just:
str + ("+".repeat(5))
String.repeat
was introduced in Java 11.
You could also just hardcode it:
String.format("%s+++++", str)
答案2
得分: 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);
英文:
String str = "Hello";
String padded = String.format("%s+++++", str);
System.out.println(padded);
?
if you want to have it more generic and extract it to the method you can try to do sth like this:
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);
答案3
得分: 1
String str = "Hello";
String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";
英文:
String str = "Hello"
String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";
答案4
得分: 1
String.format("%s%s", str, "++++");
这应该可以工作。
英文:
String.format("%s%s", str, "++++");
This should work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论