将0添加到string / int变量 [英] Adding 0's to string/int variable
问题描述
所以我一直在使用一个命名约定,在字符串之前添加0。我试图在把所有内容都转化成if语句之前,简单地做到这一点。这里我打印0之前的int给我一个00005的答案。
So I have been working on a naming convention which add 0's before a string. I'm trying to do this the short handed way before breaking everything into if statements. Here I print 0's before an int giving me an answer of 00005.
String test = null;
int n = 5;
test = String.format("%05d%n", n);
System.out.println(test);
现在我想做的是做一个String。所以例如如果String n =5;它会给我一个00005的答案,如果String n =20;这将是00020.我不希望使用整数方法将字符串更改为和int,并返回到一个字符串。任何帮助将不胜感激。谢谢!
Now what I would like to do is do this to a String. So for example if String n = "5"; it would give me an answer of 00005 and if String n = "20"; it would be 00020. I do not wish to use the integer method to change the string to and int, and back into a string. Any help would be appreciated. Thank you!
推荐答案
这个怎么样?
("00000" + numberAsString).substring(numberAsString.length())
只有您的数字数字不超过5位,才能生效。
This will only work if you have 5 or less digit numbers.
说实话,我也认为这段代码如何工作的4倍,但在理解之后,我发布了这是开箱即用的。
To be honest, I also think 4 times how this code works, but after understanding I posted as this is something out of the box.
这篇关于将0添加到string / int变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!