如何使用String.format将5个加号添加到现有字符串中?

huangapple go评论64阅读模式
英文:

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 = &quot;Hello&quot;;
String padded = String.format(&quot;%s+++++&quot;, 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 = &quot;Hello&quot;;
int size = 10;
String pluses = &quot;&quot;;
for (int i = 0; i &lt; size; i++) pluses = String.format(&quot;%s+&quot;, pluses);
String padded = String.format(&quot;%s%s&quot;, str, pluses);
System.out.println(padded);

答案3

得分: 1

String str = "Hello";

String padded = String.format("%s+++++", str);
// or
String padded = str + "+++++";
英文:
String str = &quot;Hello&quot;

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

答案4

得分: 1

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

这应该可以工作。

英文:

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

This should work.

huangapple
  • 本文由 发表于 2020年5月5日 19:30:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61612100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定