简体   繁体   English

在Java中用零填充

[英]Right padding with zeros in Java

Sorry if this question was made already, I've made a deep search and nothing.抱歉,如果这个问题已经提出,我已经进行了深入搜索,但什么也没有。

Now, I know that:现在,我知道了:

String.format("%05d", price);

Will be padding my price with zeros to the left, so a price of 25 will result in 00025将在左边用零填充我的价格,所以 25 的价格将导致00025

What if I want to pad them to the right, so the result is 25000 ?如果我想将它们填充到右侧,结果是25000怎么办? How do I do that using only String.format patterns?如何使用String.format模式来做到这一点?

You could use:你可以使用:

String.format("%-5s", price ).replace(' ', '0')

Can I do this using only the format pattern?我可以只使用格式模式吗?

String.format uses Formatter.justify just like the String.printf method. String.format使用Formatter.justify就像String.printf方法一样。 From this post you will see that the output space is hard-coded, so using the String.replace is necessary.从这篇文章中你会看到输出空间是硬编码的,所以使用String.replace是必要的。

试试这个 :

String RightPaddedString = org.apache.commons.lang.StringUtils.rightPad(InputString,NewStringlength,'paddingChar');

Please try to read this doc, look if the library of apache commons StringUtils can help you请尝试阅读此文档,看看 apache commons StringUtils库是否可以帮助您

I've made a code like this :我做了这样的代码:

import org.apache.commons.lang3.StringUtils;

public static void main(String[] args)  {   
  String str = "123";
  str = StringUtils.leftPad(str,10,"0"); //you can also look the rightPad function.
  System.out.println(str);
}

Credits to beginnersbook.com , this is a working solution for the problem:归功于beginnersbook.com ,这是该问题的有效解决方案:

public class PadRightTest {
  public static void main(String[] argv) {
    System.out.println("#" + rightPadZeros("mystring", 10) + "@");
    System.out.println("#" + rightPadZeros("mystring", 15) + "@");
    System.out.println("#" + rightPadZeros("mystring", 20) + "@");
  }

  public static String rightPadZeros(String str, int num) {
    return String.format("%1$-" + num + "s", str).replace(' ', '0');
  }
}

and the output is:输出是:

#mystring00@
#mystring0000000@
#mystring000000000000@

Use this function for right padding.使用此函数进行右填充。

private String rightPadding(String word, int length, char ch) {
   return (length > word.length()) ? rightPadding(word + ch, length, ch) : word;
}

how to use?如何使用?

rightPadding("25", 5, '0');

In my case I solved this using only native Java.就我而言,我仅使用本机 Java 解决了这个问题。

StringBuilder sb = new StringBuilder("1234");
sb.setLength(9);
String test = sb.toString().replaceAll("[^0-9]", "0");
System.out.println(test);

So it printed out : 123400000所以它打印出来:123400000

如果您想不使用格式或任何功能,请使用这个简单的技巧System.out.println(price+"000");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM