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

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

How to add 5 pluses to an existing string using String.format?

问题

怎样使用String.format在现有字符串中添加5个加号?

我知道可以通过以下方式在现有行中添加空格:

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

怎样添加加号?
我没有找到如何表示加号符号。

结果应该是:

  1. "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:

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

How to add plus?
I did not find how the plus symbol is indicated.

the result should be:

  1. "Hello+++++"

答案1

得分: 3

没有标志允许您填充+而不是空格。相反,您需要这样做:

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

或者可能只需:

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

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

您还可以直接编码:

  1. String.format("%s+++++", str)
英文:

There is no flag that allows you to pad + instead of space. Instead you need to do something like:

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

or maybe just:

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

String.repeat was introduced in Java 11.

You could also just hardcode it:

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

答案2

得分: 1

  1. String str = "Hello";
  2. String padded = String.format("%s+++++", str);
  3. System.out.println(padded);
  4. // 如果您想更通用地将其提取到方法中,您可以尝试像这样做:
  5. String str = "Hello";
  6. int size = 10;
  7. String pluses = "";
  8. for (int i = 0; i < size; i++) pluses = String.format("%s+", pluses);
  9. String padded = String.format("%s%s", str, pluses);
  10. System.out.println(padded);
英文:
  1. String str = &quot;Hello&quot;;
  2. String padded = String.format(&quot;%s+++++&quot;, str);
  3. 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:

  1. String str = &quot;Hello&quot;;
  2. int size = 10;
  3. String pluses = &quot;&quot;;
  4. for (int i = 0; i &lt; size; i++) pluses = String.format(&quot;%s+&quot;, pluses);
  5. String padded = String.format(&quot;%s%s&quot;, str, pluses);
  6. System.out.println(padded);

答案3

得分: 1

  1. String str = "Hello";
  2. String padded = String.format("%s+++++", str);
  3. // or
  4. String padded = str + "+++++";
英文:
  1. String str = &quot;Hello&quot;
  2. String padded = String.format(&quot;%s+++++&quot;, str);
  3. // or
  4. 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:

确定