我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
我在这里和这里都见过类似的问题。
但我不知道如何左垫字符串与零。
输入:“129018” 输出:“0000129018”
总输出长度应为10。
当前回答
基于@Haroldo Macêdo的回答,我在自定义Utils类中创建了一个方法,例如
/**
* Left padding a string with the given character
*
* @param str The string to be padded
* @param length The total fix length of the string
* @param padChar The pad character
* @return The padded string
*/
public static String padLeft(String str, int length, String padChar) {
String pad = "";
for (int i = 0; i < length; i++) {
pad += padChar;
}
return pad.substring(str.length()) + str;
}
然后打电话给Utils。padLeft(str, 10, "0");
其他回答
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());
}
}
如果你的字符串只包含数字,你可以让它成为一个整数,然后做填充:
String.format("%010d", Integer.parseInt(mystring));
如果没有,我想知道如何才能做到。
右填充固定长度-10: 字符串。格式(“% 1 $ -10年代”,“abc”) 左填充固定长度-10: 字符串。格式(“% 1 $ 10 s”、“abc”)
检查我的代码,将工作的整数和字符串。
假设第一个数字是129018。我们要给它加上0所以最终字符串的长度是10。为此,您可以使用以下代码
int number=129018;
int requiredLengthAfterPadding=10;
String resultString=Integer.toString(number);
int inputStringLengh=resultString.length();
int diff=requiredLengthAfterPadding-inputStringLengh;
if(inputStringLengh<requiredLengthAfterPadding)
{
resultString=new String(new char[diff]).replace("\0", "0")+number;
}
System.out.println(resultString);
格式化字符串使用
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