我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
当前回答
格式化字符串使用
import org.apache.commons.lang.StringUtils;
public class test {
public static void main(String[] args) {
String result = StringUtils.leftPad("wrwer", 10, "0");
System.out.println("The String : " + result);
}
}
输出:字符串:00000wrwer
其中第一个参数是要格式化的字符串,第二个参数是所需输出长度的长度,第三个参数是字符串要填充的字符。
使用链接下载罐子http://commons.apache.org/proper/commons-lang/download_lang.cgi
其他回答
右填充固定长度-10: 字符串。格式(“% 1 $ -10年代”,“abc”) 左填充固定长度-10: 字符串。格式(“% 1 $ 10 s”、“abc”)
我用过这个:
DecimalFormat numFormat = new DecimalFormat("00000");
System.out.println("Code format: "+numFormat.format(123));
结果:00123
我希望它对你有用!
int number = -1;
int holdingDigits = 7;
System.out.println(String.format("%0"+ holdingDigits +"d", number));
刚刚在采访中问过这个问题........
我的答案如下,但这个(上面提到的)要好得多——>
管柱。format(“% 05d”,全国矿工工会);
我的回答是:
static String leadingZeros(int num, int digitSize) {
//test for capacity being too small.
if (digitSize < String.valueOf(num).length()) {
return "Error : you number " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";
//test for capacity will exactly hold the number.
} else if (digitSize == String.valueOf(num).length()) {
return String.valueOf(num);
//else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError
//else calculate and return string
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < digitSize; i++) {
sb.append("0");
}
sb.append(String.valueOf(num));
return sb.substring(sb.length() - digitSize, sb.length());
}
}
这将填充左侧任何字符串的总宽度为10,而不用担心解析错误:
String unpadded = "12345";
String padded = "##########".substring(unpadded.length()) + unpadded;
//unpadded is "12345"
//padded is "#####12345"
如果你想要右填充:
String unpadded = "12345";
String padded = unpadded + "##########".substring(unpadded.length());
//unpadded is "12345"
//padded is "12345#####"
你可以用任何你想要填充的字符替换“#”字符,重复你想要的字符串的总宽度的次数。例如,如果你想在左边加0,使整个字符串长度为15个字符:
String unpadded = "12345";
String padded = "000000000000000".substring(unpadded.length()) + unpadded;
//unpadded is "12345"
//padded is "000000000012345"
与khachik的答案相比,这个答案的好处是它没有使用Integer。parseInt,它可以抛出异常(例如,如果您想要填充的数字太大,如12147483647)。缺点是,如果填充的对象已经是int类型,那么必须将其转换为String类型,然后再转换回来,这是不可取的。
所以,如果你确定它是整数,khachik的答案就很好。如果不是,那么这是一个可能的策略。
我更喜欢这样的代码:
public final class StrMgr {
public static String rightPad(String input, int length, String fill){
String pad = input.trim() + String.format("%"+length+"s", "").replace(" ", fill);
return pad.substring(0, length);
}
public static String leftPad(String input, int length, String fill){
String pad = String.format("%"+length+"s", "").replace(" ", fill) + input.trim();
return pad.substring(pad.length() - length, pad.length());
}
}
然后:
System.out.println(StrMgr.leftPad("hello", 20, "x"));
System.out.println(StrMgr.rightPad("hello", 20, "x"));